C++ Input Validation
Input Validation
When users enter data into a program, they might type something unexpected. Input validation makes sure the input is correct before your program continues.
Without validation, your program might crash or behave incorrectly!
The examples below show simple ways to check if the user's input is valid.
Validate Integer Input
Make sure the user enters a number. If they enter something else (like a letter), ask again:
int number;
cout << "Enter a number: ";
while (!(cin >> number)) { // Keep asking until the user enters a
valid number
cout << "Invalid input. Try again: ";
cin.clear(); // Reset input errors
cin.ignore(10000, '\n'); // Remove bad input
}
cout << "You entered: " << number;
Validate Number Range
Check if the number is within an allowed range (e.g. 1 to 5):
int number;
do {
cout << "Choose a number between 1 and 5: ";
cin >> number;
} while (number < 1 || number> 5); // Keep asking until the user
enters a number between 1 and 5
cout << "You chose: " << number;
Validate Text Input
Check that a name is not empty:
string name;
do {
cout << "Enter your name: ";
getline(cin, name);
} while (name.empty()); // Keep asking until the user enters something
(name is not empty)
cout << "Hello, " << name;
Tip: You can read more about the cin
object in our
<iostream> library reference.