The following code works as intended when it is given 2 integers, however if a non numeric value (like 'a') is given, it skips the second cin.
int num1; // lesser integer value input by user
int num2; // greater integer value input by user
cout << "\n\nNumber 1: ";
cin >> num1;
cout << "Number 2: ";
cin >> num2;
if (!cin)
{
cout <<"\nError" <<endl;
return 0;
}
When entering a number for the first prompt the program carries on, however if something like a
is entered for the first prompt, it skips the second prompt and hits the error condition
When the formatted input operator >>
fails (like for example you give a
as input when a number was expected) the input in the buffer is not removed, it's still there for the next time you want to read input (which will attempt to read the very same a
again).
The flags are also not cleared automatically.
You could solve this by checking when you read the input:
if (!(std::cin >> num1))
{
// Failure of some kind
if (std::cin.eof())
{
// End of file, handle this any way you like or need
}
else
{
// Not end-of-file
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Skip bad input
std::cin.clear(); // Clear error flags
}
}
References:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments