(I'm going to back up a little bit to explain this)
So when the user enters something that's not an
kicks up an error flag and line 9 becomes
as a result.
You need to clear that error flag first before you do any other input operations with cin
, which is why line 12 is needed (it clears all error flags).
But the gibberish that you inputted is still there, so that all has to get cleared out as well before you can try again to input a number.
basically does this for you (line 13).
Technically, you could just do something like
(which will discard 1000 characters or until it reaches a newline character), but that won't work if you type 1001 characters (or more) of gibberish, since it'll only get rid of the first 1000. (But if you know for sure that nobody who's going to use this program would ever even think about inputting 1001 characters, then this might be okay. Of course, you can't really assume that other people won't be tempted to try....)
So the "proper" way is to use
, which tells the function to discard as many characters as possible until a newline character is reached. (You'll need to
to use it, though)
You can read more about it here: