i'm using a simple switch statement to get user input. from 1 to 5.
what if they enter a letter, whilst my cin is expecting an int. is there a way to catch that before it causes problems with my program?
Printable View
i'm using a simple switch statement to get user input. from 1 to 5.
what if they enter a letter, whilst my cin is expecting an int. is there a way to catch that before it causes problems with my program?
Test the input stream after the attempt is made to read the number. If the stream is in an error state, then something happened and you should clear the error state, dump the contents of the stream and ask the user for more (and hopefully valid) input.
Code:#include <limits>
...
int value;
cout << "Enter an int: ";
while( !(cin >> value) )
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "I said enter an int you idiot: ";
}
...
// continue on with rest of code