Say I have a program that takes in integers. How do I stop the program from falling apart if the user enters an out of range number, or a letter or something?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
cin‘s base class isstd::basic_istream. The input stream indicates a recoverable error in case it cannot extract the requested data from the stream. In order to check for that error bit,std::basic_istream::fail()method must be used — it returnstrueif there was a failure orfalseif everything is alright. It is important to remember that if there is an error, the data is left in the stream and, of course, the error bit(s) must also be cleared usingstd::basic_istream::clear(). Also, a programmer must ignore incorrect data, or otherwise an attempt to read something else will fail again. For that purpose,std::basic_istream::ignore()method can be used. As for the valid range of values, it must be checked manually. Okay, enough theory, here is a simple example:Hope it helps. Good Luck!