Validating User Input in C++
How can I validate user input to ensure it's the correct data type?
Validating user input is crucial for creating robust C++ programs. Here's a guide on how to ensure your input is of the correct data type:
Using Error States
When reading input with std::cin
, it sets error flags if the input doesn't match the expected type. We can use these flags to validate input:
#include <iostream>
#include <limits>
int main(){
int userAge;
while (true) {
std::cout << "Enter your age: ";
std::cin >> userAge;
if (std::cin.fail()) {
std::cin.clear(); // Clear error flags
std::cin.ignore(
std::numeric_limits<
std::streamsize>::max(),
'\n');
std::cout
<< "Invalid input. Please enter a number.\n";
} else if (userAge <= 0 || userAge > 120) {
std::cout <<
"Age must be between 1 and 120.\n";
} else {
break; // Valid input, exit loop
}
}
std::cout << "Your age is: " << userAge;
}
Enter your age: hi
Invalid input. Please enter a number.
Enter your age: 25
Your age is: 25
In this example, we use a while loop to repeatedly ask for input until it's valid. The std::cin.fail()
check detects if the input wasn't an integer. If it fails, we clear the error flags and ignore the rest of the input line.
Using String Input and Conversion
Another approach is to read input as a string and then convert it:
#include <iostream>
#include <string>
#include <stdexcept>
int main(){
std::string input;
int userAge;
while (true) {
std::cout << "Enter your age: ";
std::getline(std::cin, input);
try {
userAge = std::stoi(input);
if (userAge <= 0 || userAge > 120) {
throw std::out_of_range(
"Age out of valid range");
}
break; // Valid input, exit loop
}
catch (const std::invalid_argument&) {
std::cout
<< "Invalid input. Please enter a number.\n";
} catch (const std::out_of_range&) {
std::cout <<
"Age must be between 1 and 120.\n";
}
}
std::cout << "Your age is: " << userAge;
}
Enter your age: hi
Invalid input. Please enter a number.
Enter your age: 25
Your age is: 25
This method uses std::getline()
to read the entire input line, then std::stoi()
to convert it to an integer. We catch exceptions to handle invalid input or out-of-range values.
Remember, input validation is about more than just checking data types. Always consider the range of acceptable values and any other constraints specific to your program's needs.
User Input in the Terminal
This lesson introduces the fundamentals of capturing user input, using std::cin
and std::getline()