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?