I get the loop, and the initial prompt for input of type int, but… what is the while loop checking with !(cin >> [variable])? I looked at cin on cplusplus.com for an explanation but I don’t see it holding any value … it looks like it’s just checking the numerical value of the number entered, how would that check for a valid integer input?
int number;
.
.
.
cout<<"Please enter a number: ";
while (!(cin >> number))
{
cin.clear();
cin >> badinput;
cout <<"Input " << badinput << " is invalid, please enter a number: ";
}
operator >>on an input stream returns a reference to the stream, not the thing read from the stream. The value read is placed into what the argument references, which must be an lvalue.The
!operator on an iostream tests the failure flag on on the stream — it returns true if there’s been any sort of failure on the stream. For an input stream, if you attempt to read an integer (as this code is doing) and the input doesn’t look like an integer, the fail flag will be set.So this code (attempts to) read an integer into
numberand then tests the fail flag. If it’s set, it clears the fail flag, readsbadinput(probably a string), prints the message and loops, attempting to read another integer.So as long as the only failure is with the formatting, it will loop until it gets an integer. If there’s some other more persistent failure (eg, if cin gets an EOF or is closed), it will loop forever.