Derscription of this function:
1 2 3 4 5 6 7 8 9 10 11 12
|
int getInteger()
{
int n;
while (!(cin >> n))
{
cin.clear(); // not valid, clear status flags
cin.ignore(1000, '\n'); // discard rest of line
}
return n;
}
|
We could write the code like this:
1 2 3 4 5 6 7 8
|
int n; // declare an integer
cin >> n; // attempt to get an integer from cin
if ( cin.fail() ) // test the status of cin to see if it failed
{
// action to be taken if the input failed.
}
|
In the original code,
this line first attempts to read an integer, then checks the status of cin. If the input failed, the condition will be true and the body of the loop will be executed.
The rest of the code is taken in order to clear up the mess.
First, the fail() flag was set. We need to reset (clear) the flag before we are able to use cin again. That is what
cin.clear();
does.
Now we are able to use cin. But we know the previous input caused a failure, there is some invalid input. That input remains in the input buffer. It needs to be removed. Since we don't know for sure what was typed, all we can do is to ignore the input until the end of the line.
cin.ignore()
on its own will read and discard a single character.
cin.ignore(1000, '\n');
will ignore up to 1000 characters, or until the newline character
'\n'
is found.