I recently created a program that will create a math problem based on the user input. By entering either 1-4 the program can generate a problem or the user can quit by ente
First off, you should detect whether your input attempt was successful: always check after reading that the read attempt was successful. Next, when you identify that you couldn't read a value you'll need to reset the stream to a good state using clear()
and you'll need to get rid of any bad characters, e.g., using ignore()
. Given that the characters were typically entered, i.e., the user had to hit return before the characters were used it is generally reaonable to get of the entire line. For example:
for (choice = -1; !(1 <= choice && choice <= 5); ) {
if (!(std::cin >> choice)) {
std::cout << "invalid character was added (ignoring the line)\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
The use of std::numeric_limits<std::streamsize>::max()
is the way to obtain the magic number which makes ignore()
as many characters as necessary until a character with the value of its second argument is found.
You can use isdigit from ctype.h
Actually, forget about step 2. Just check whether it was one of the digit characters you actually want ('1'
, '2'
, '3'
, '4'
, '5'
):
char choice;
while(cin.get(choice)){
if(choice == '5')
break;
switch(choice){
default: printWrongCharacterMessage(); break;
case '1': do1Stuff(); break;
case '2': do2Stuff(); break;
case '3': do3Stuff(); break;
case '4': do4Stuff(); break;
}
}