So I’m curious as to why this happens.
int main()
{
bool answer = true;
while(answer)
{
cout << "\nInput?\n";
cin >> answer;
}
return 0;
}
Expected behavior:
0 – Exits program,
1 – Prompts again,
Any non-zero integer other than 1 – Prompts again
Actual behavior:
0 – As expected,
1 – As expected,
Any non-zero integer other than 1 – Infinite loop
From http://www.learncpp.com/cpp-tutorial/26-boolean-values/
One additional note: when converting integers to booleans,
the integer zero resolves to boolean false,
whereas non-zero integers all resolve to true.
Why does the program go into an infinite loop?
In effect, the
operator>>overload used for reading aboolonly allows a value of0or1as valid input. The operator overload defers to thenum_getclass template, which reads the next number from the input stream and then behaves as follows (C++11 §22.4.2.1/6):(
errhere is the error state of the stream from which you are reading;cinin this case. Note that there is additional language specifying the behavior when theboolalphamanipulator is used, which allows booleans to be inserted and extracted using their names,trueandfalse; I have omitted these other details for brevity.)When you input a value other than zero or one, the fail state gets set on the stream, which causes further extractions to fail.
answeris set totrueand remainstrueforever, causing the infinite loop.You must test the state of the stream after every extraction, to see whether the extraction succeeded and whether the stream is still in a good state. For example, you might rewrite your loop as: