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?
This is a discussion on cin expecting number but gets a letter within the C++ Programming forums, part of the General Programming Boards category; i'm using a simple switch statement to get user input. from 1 to 5. what if they enter a letter, ...
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
I used to be an adventurer like you... then I took an arrow to the knee.