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()

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Changing Console Input Color in C++
Can I change the color or formatting of the input prompt in the console?
Formatting Console Output in C++
How can I format console output to create more visually appealing displays?
Secure Password Input in C++
How do I handle password input where characters should not be displayed?
Handling Arrow Key Input in C++
Is it possible to get arrow key input in C++ for navigation purposes?
Multiple Inputs on a Single Line in C++
Is it possible to input multiple values in a single line using std::cin?
Handling Spaces in User Input
How do I handle spaces in user input when using std::cin?
std::cin vs std::getline() in C++
What's the difference between using std::cin >> and std::getline()?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant