-
Switch problem
Hi all
Surprised I haven't been able to find a solution to this when it must be a common problem...
I am having trouble with a switch statement that is nested in a forever loop. The user is to input an unsigned short to determine which case the program should jump to. My problem is that if the user inputs a letter instead of a number, the program then keeps looping forever rather than simply going to the default case. Can anyone tell me how to fix this?
Many thanks :-)
John
-
You'll need to check the state of the input stream:
Code:
unsigned i;
while (!(cin >> i)) {
cin.clear(); //clear error status
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard any unread characters
}
//now i contains input
You might also check if the input error was eof, and break from the infinite loop in this case: may-be the user really wants to stop.