+ 1
Little help please. What if the user input a STRING here (ex. dog). How can I make an output that says "Invalid Input"?
2 ответов
+ 7
I have modified your code and added a check for string literals plus check for strings with blanks and whitespaces as well using the following code-
char dummy = '\0';
if (!(cin >> x) || (cin >> ws && cin.get(dummy)))
cout << "Invalid input. Try again!\n";
It is working well for me! 😇
https://code.sololearn.com/c2p1lWFV5n5i/?ref=app
+ 8
Exception handling.
try
{
cin >> input;
if (cin.fail()) throw 1;
// more codes
}
catch(int err)
{
switch(err)
{
case 1: cin.clear();
cin.ignore(512, '\n');
cout << "Invalid input.";
// more cases
}
}