-1

To catch a invalid numerical input, I found a code template as follows:

#include <limits>

int x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail()) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    std::cout << "Invalid Input. Re-enter a NUMBER: ";
    std::cin >> x;
}
std::cout << "x = " << x << std::endl;

But what if user inputs a numerical value instead of a string? For an example: in a case like following;

string name;
std::cout << "Enter your Name: ";
std::cin >> name;   // the user inputs a number as the input

Is there any way to catch that?

In this case I tried modifying the data types of the template as follows:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;
    while (cin.fail()){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        std::cout << "Bad entry.  Enter a Name: ";
        std::cin >> name;
    }

    cout << "\n" << name << endl;

    return 0;
}

I tried passing numbers as inputs but compiler passed them as strings and gave me the numbers as the output, no errors.

Are there any modifications for the above code or is there any method to resolve this?

  • Use an if condition to check the user input for invalid characters. – binaryescape Aug 05 '23 at 19:30
  • 1
    The possible name "123" is legal. Why do you want to reject it? – 273K Aug 05 '23 at 19:30
  • @273 you're right, OP should be more tolerant, "X Æ A-12" is in fact a valid name. – binaryescape Aug 05 '23 at 19:32
  • @binaryescape Yes in the US, but I'm sure there are use cases for which one might want to reject numeric input. For an arbitrary and artificial example, perhaps someone in some military training camp wants to enforce short alphabetic nicknames. ... – Lover of Structure Aug 05 '23 at 19:38
  • @123 ... That is, I think the question can still be answered. (That said, I do agree that overly restrictive integrity checks can be a nuisance, like if a bank insists on 10-digit phone numbers, thereby inconveniencing customers who don't live in the US.) – Lover of Structure Aug 05 '23 at 19:39
  • Plus, please everyone keep in mind that this is likely a toy example. That is, OP may just want to learn and experiment, which makes for a valid question. – Lover of Structure Aug 05 '23 at 19:47
  • Yes, you can check the string to see if it matches your definition of a valid string. There is no automatic method to do this, but if this is something you want to do you can write some code to do whatever check you want. – john Aug 05 '23 at 20:10

0 Answers0