That code isn't exactly complete, since it doesn't tell you how to clear the stream of errors and ask again. I prefer this method of checking for integers:
Code:
int number = 0;
while (!(cin >> number) || cin.get() != '\n')
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// output your error message here and tell the user to try again.
}
Here's what it doesIf cin fails to read in an int, it goes into a fail state. For example, if the user types characters like "abc", that isn't an int. Checking the return value allows you to check for the fail state. So if cin >> number fails, then it will evaluate to false and !(cin >> number) will be true. So if it fails, we'll enter the loop to clear the error and try again.
Code:
|| cin.get() != '\n'
If the input doesn't fail, then we check the next character. If the user types a number and hits enter, then it should be a newline, which is '\n'. If it is not a newline, then the user typed extra characters. So for example if the user types "123.0" or "123abc", this second part will be true and the code will enter the error handling loop.This clears the failbit. If the loop was entered because the read failed, then this clears that flag so you can try to read again. If the fail bit is not set this does nothing, so it is safe to call here.
Code:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
This ignores all characters (up to the newline) in the buffer. It gets rid of all the bad input so the user can try again with a clean bluffer. You could also use int instead of streamsize, or even cin.ignore(1000, '\n');. The difference is that 1000 will ignore a maximum of 1000 characters, so if the user types in more than 1000 characters, they won't all be ignored. Using the numeric_limits version makes sure you ignore them all just in case.
So overall, you try to read a number. If it fails or there are extra garbage characters, you clear and empty the cin stream and try again. You keep doing this in a loop until the user enters a number.
Code:
if (!cin || cin.gcount() != 1)
In that code, the !cin is like the !(cin >> number) I used, it just checks cin later. The cin.gcount != 1 is like the cin.get() != '\n', it checks to make sure there is only one character (the newline) left in the stream.