#include <iostream>
usingnamespace std;
int main()
{
int x;
while(1)
{
cin>>x;
if(x == 1)
{
cout<<"The number is one"<<endl;
break;
}
elseif(x == 2)
{
cout<<"The number is two"<<endl;
break;
}
else
cout<<"The input must be 1 or 2"<<endl;
}
}
If you enter a character instead of an integer it keeps couting "The input must be 1 or 2" into infinity. How can this be stopped?
Thanks in advance.
When the stream cannot read what is expected from it (it tries to read an int, but gets whatever else), the stream sets the "fail" flag to signify a problem and does nothing to the variable "x". So the loop continues with whatever value that was in "x" (which is undefined, and in your case something else than 1 or 2). Then it tries to read again from the input, it does nothing because the stream is in a fail state and the same happens again (x not 1 or 2, output a message and go to next iteration).
So to fix that you have to check if the stream failed to read a value for "x" and if it did fail - restore the cin's state to good, showing that it's ok to read on, and ignore everything that is left in the buffer, so the next read operation doesn't fail on the trying to interpret the same incorrect input.
You can do it like this:
1 2 3 4 5 6
if (!(cin>>x)) { // streams have conversion-to-bool operator which returns false if something went wrong
cin.clear(); // restore the good state
cin.ignore(); // ignore the incorrect input
continue; // try again
}
Honestly, you do not need a loop for what it seems you are trying to do. But, if you use one make sure the condition in the while parameter is accurate. The code below works just fine with the while loop
int main()
{
int x;
cin>>x;
while(x>0||x<0)
{
if(x == 1)
{
cout<<"The number is one"<<endl;
break;
}
elseif(x == 2)
{
cout<<"The number is two"<<endl;
break;
}
else
cout<<"The input must be 1 or 2"<<endl;
break;
}
}
@dtaqee What I want to do, is ask for input again if the input is not 1 or 2. In your example you wouldn't need a loop at all.
@KRAkatau So if I understand this correctly, because the cin is expecting an integer, but receives a character, it breaks down, failing to operate correctly, and thus skipping the cin>>x; I tried your solution, and it worked. Thank you very much.
Yes, you understand it correctly. Although, it's not so much a "breakdown", but rather a way of telling the user that something went not as expected and giving him a chance to recover from an error.