User Input in the Terminal

Validating User Input in C++

How can I validate user input to ensure it's the correct data type?

Abstract art representing computer programming

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.

This Question is from the Lesson:

User Input in the Terminal

This lesson introduces the fundamentals of capturing user input, using std::cin and std::getline

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

User Input in the Terminal

This lesson introduces the fundamentals of capturing user input, using std::cin and std::getline

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 57 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved