Quote:Original post by BUnzaga
In the javascript code I have been using, I would use something like i1=null. Is there something like that in C++?
The stream doesn't care about i1. If reading fails, i1 has not even been modified. The problem here is about the stream contents, not the integer.
Suppose you enter the text "Hello" at the prompt. So, the beginning of standard input is "Hello". Then, std::cin >> i1 attempts to read "Hello" as an integer. It fails, because "Hello" is not a valid integer, which places std::cin in an invalid state, leaves "Hello" in the stream, and does not modify the integer.
Your code then calls std::cin.clear() to notify std::cin that you are aware of the error. Note that the beginning of standard input is still "Hello", as no successful read operation has been performed so far. Then, your loop repeats, and you try to perform std::cin >> i1 again. Note that the contents or the input stream are still "Hello", because you have not done anything with the stream to change its contents, so the reading of "Hello" as an integer fails again.
Your code then calls std::cin.clear() again to notify std::cin that you are aware of the new error. Again, note that the beginning of standard input is still "Hello", as you have still not managed to perform a succesful read operation on your stream. Your loop repeats once more, and the code executes std::cin >> i1 for a third time. The input stream still starts with "Hello", because its contents have still not been altered by a successful read, so reading it as an integer fails once more.
This cycle repeats on and on, without any reason to stop. Basically, your program reaches the situation "the stream contains invalid data", to which you respond "do not worry, try again", where a sane answer would be "do not worry, remove the invalid data, then try again".