int nX;
while (1)
{
cin >> nX;
if (nX == 1)
break;
elseif (nX == 2)
break;
elseif (nX == 3)
break;
else
cout << "Please enter a valid answer: " << endl;
}
If I enter any number other than 1 2 or 3 the program outputs
4
Please enter a valid answer:
until I pick a number 1-3.
If I enter letters though it outputs
c
Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer: Please enter a valid answer:
endlessly
I'm not sure why it's doing this isn't 'c' supposed to evaluate to 99?
also why is "c" == 4644900?
EDIT: I think 4644900 might be a pointer but I'm not sure can someone confirm this?
When you input 'c', cin will go into an error state because it was expecting a number. You have to clear out the junk yourself then .clear() cin to clear the error state.
When you enter a character when cin is supposed to stream input to an int, cin sets a fail flag. Once that happens, no calls to "cin >>" will occur until the flags are reset.
So after displaying "Please enter a valid answer: ", the loop goes to line 5, which is skipped over because one of the fail flags is set. This leaves nX unchanged, so the else statement is executed again.
I think you would be better off with a switch statement inside a while loop. Have a default case to handle bad input, and a quit case. The while loop is controlled by a boolean variable.