cin will not store characters in an integer.
If you query for an integer using cin, and the user enters one or more characters (followed by 'enter'), then cin will fail. You can verify this by calling cin.fail().
To clear cin's error state, you need to call cin.clear(), followed by a call to cin.ignore() remove unwanted characters from the data stream.
For example:
PHP Code:
...
int value = 0;
while (true)
{
std::cout << "Enter a number: ";
std::cin >> value;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(1024, '\n'); // ignore at most 1024 characters until '\n' found
}
else
break; // all good; we got a value
}
...
Bookmarks