In C++, how do you handle wrong inputs? Like, if the program asks for an integer, when you type a character it should be able to do something and then loop to repeat the input but the loop goes infinite when you input a character when an integer is need and vice versa.
Share
The reason the program goes into an infinite loop is because
std::cin‘s bad input flag is set due to the input failing. The thing to do is to clear that flag and discard the bad input from the input buffer.See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.
Another way would be to get the input as a string and convert it to an integer with
std::stoior some other method that allows checking the conversion.