c++ - How to handle wrong data type input -
in c++, how handle wrong inputs? like, if program asks integer, when type character should able , loop repeat input loop goes infinite when input character when integer need , vice versa.
the reason program goes infinite loop because std::cin's bad input flag set due input failing. thing clear flag , discard bad input input buffer.
//executes loop if input fails (e.g., no characters read) while (std::cout << "enter 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 this, , other examples, including adding minimum and/or maximum condition.
another way input string , convert integer std::stoi or other method allows checking conversion.
Comments
Post a Comment