Validate User Input in C++

  1. Use cin With cin.clear and cin.ignore Methods to Validate User Input
  2. Use Custom Defined Function to Validate User Input

This article will demonstrate multiple methods about how to validate user input in C++.

Use cin With cin.clear and cin.ignore Methods to Validate User Input

This example focuses on a robust user input validation method, meaning it should satisfy basic error checking requirements and continue executing even when the input is of the wrong type.

The first construct to implement this feature is the while loop, and we are going to specify true in a condition. This iteration will guarantee recurring behavior until the correct value is stored in a variable. Inside the loop, an if statement evaluates cin >> var expression because the return value is positive on a successful insert operation. Once the value is correctly stored, we can exit the loop; otherwise, if the cin expression did not succeed, the execution moves onto the cin.clear call, which unsets the failbit after unexpected input. Next, we skip through the leftover characters in the input buffer and go to the next iteration to ask the user.

#include <iostream>
#include <sstream>
#include <limits>
#include <vector>

using std::string; using std::vector;
using std::cout; using std::endl;
using std::cin; using std::numeric_limits;

int main()
{
    int age;

    while (true) {
        cout << "Enter the age of the wine: ";
        if (cin >> age) {
            break;
        } else {
            cout << "Enter a valid integer value!\n";
            cin.clear();
            cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    return EXIT_SUCCESS;
}

Output:

Enter the age of the wine: 32

Use Custom Defined Function to Validate User Input

The previous method could be quite cumbersome for even several input variables, and the code space would be wasted with multiple while loops. Thus, the subroutine should be generalized as a function. validateInput is the function template that takes the variable’s reference and returns the successfully stored value.

Notice that, even if we need to implement a 100 question quiz, this method guarantees far cleaner code than the previous version would yield.

#include <iostream>
#include <sstream>
#include <limits>
#include <vector>

using std::string; using std::vector;
using std::cout; using std::endl;
using std::cin; using std::numeric_limits;

template<typename T>
T &validateInput(T &val)
{
    while (true) {
        cout << "Enter the age of the wine: ";
        if (cin >> val) {
            break;
        } else {
            cout << "Enter a valid integer value!\n";
            cin.clear();
            cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    return val;
}

int main()
{
    int age;
    int volume;
    int price;

    age = validateInput(age);
    volume = validateInput(volume);
    price = validateInput(price);

    cout << "\nYour order's in!\n" << age << " years old Cabernet"
         << " in " << volume << "ml bottle\nPrice: " << price << "$\n";

    return EXIT_SUCCESS;
}

Output:

Enter the age of the wine: 13
Enter the volume of the wine in milliliters: 450
Enter the price of the bottle: 149

Your order's in!
13 years old Cabernet in 450ml bottle
Price: 149$

Related Article - C++ IO

  • Use cin.fail Method in C++
  • Right Justify Output in C++