How to handle wrong data type input

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.

//executes loop if the input fails (e.g., no characters were read)
while (std::cout << "Enter a number" && !(std::cin >> num)) {
    std::cin.clear(); //clear bad input flag
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
    std::cout << "Invalid input; please re-enter.\n";
}

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::stoi or some other method that allows checking the conversion.

Leave a Comment