Loading lessons...
Input Validation
Input Validation
Users type whatever they want. Input validation is the process of checking what a user entered before you trust it. C++ won't stop a user from typing "hello" when your program asks for a number.
The problem: what does cin do?
int x;
cin >> x; // what if the user types "abc"?
With non-numeric input, cin does not crash and does not throw - it silently leaves x at its old value and sets a failure flag inside the stream.
Reading an int safely and loop until good
The robust pattern is: read, check the stream state, clean up, and try again in a loop.
int x;
cin >> x;
while (cin.fail()) {
cin.clear(); // fix the fail flag
cin.ignore(1000, '\n'); // consume the bad characters
cout << "Not a number, try again: ";
cin >> x;
}
cin.fail()is true when the extraction failed.cin.clear()resets the failure state.cin.ignore()drops the bad leftover input.
That loop repeats until an actual number arrives.
Looping until valid input
You can also add your own rules, for example an integer in range:
int age;
do {
cout << "Age (1 to 120): ";
cin >> age;
} while (age < 1 || age > 120);
The loop keeps asking until age satisfies the range. Testing the stream state first avoids problems inside whatever loops.
The broad outline
The shape is always the same: ask, try to read, inspect the stream state, clear and ignore when needed, and repeat. Validate early, so bad input is stopped at the door and never reaches your calculations.
TL;DR
cinsets a failure flag instead of throwing on bad input.cin.fail()reports whether the last read failed.cin.clear()resets the flag so you can read again.cin.ignore()discards the leftover bad input.- Loop until the input is valid before using it.