C++ ErrorsLesson 46Free preview
C++ Input Validation
This lesson is part of C++ · All levels
Summary
Input validation ensures that the data entered by the user is in line with the program's expectations, such as numbers that are actually numbers and are within a reasonable range. If the user enters text when asked for a number, the stream enters a failed state (file) so it must be returned with cin.clear() and the remaining characters are discarded with cin.ignore(). This pattern prevents the program from getting into endless repetitions or messy results.
Key points
- Cin >> x on the invalid input causes the stream to enter the state file and the x is not filled.
- Cin.clear() restore the stream to good condition.
- Cin.ignore(numeric_limits<streamsize>::max(), '\n') discarded the remaining problem input.
- Range validation is performed with a while/do-while loop until the input is correct.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.