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?
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?
werdy666!
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
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens