First, you must determine if your typing attempt was successful: always check after that the read attempt was successful. Then, when you find that you cannot read the value, you need to reset to transfer the stream to a good state with clear() , and you will need to get rid of any bad characters, for example, using ignore() , given that the characters are usually , were entered, that is, the user had to strike back before the characters were used, he, as a rule, can be used to get the entire line. For instance:
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'); } }
Using std::numeric_limits<std::streamsize>::max() is a way to get a magic number that ignore() makes as many characters as possible until a character with the value of its second argument is found.
source share