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

Popular posts from this blog

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

javascript - Confirm a form & display message if form is valid with JQuery -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -