Question: C++ Input Validation When a program is trying to read an int from cin and you enter something non-numeric , the cinstream goes into the

C++

Input Validation

When a program is trying to read an int from cin and you enter something non-numeric, the cinstream goes into the fail-state.

correctly handle such invalid input

How to detect: If the operation cin >> x fails to read the input and the stream goes into the fail-state, the expression cin >> x returns false, indicating the failure. We have used this fact in the past to read until the end of the file. Alternatively, you may also check if the stream is in the fail-state using cin.fail().

How to recover cin: Once you have identified that the stream is in the fail-state, to return it into the good-state, use these two commands:

 cin.clear(); cin.ignore(); 

Write a C++ program which fixes the observed issue by validating the user input. When reading numeric parameters, the program should ensure that the user re-enters the value in case of input failure (make them re-enter it until the user input is correctly).

Because several places in the program that will require such input validation, write a function that reads a numeric and makes the user re-enter it until they do it correctly.

Thank you.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!