C++ Input Validation


User input is one of the most common sources of bugs and errors in any program. Users might accidentally or intentionally enter data that the program isn’t prepared to handle. Input validation is the process of ensuring that the data entered by the user is correct, meaningful, and within the expected range before the program uses it.

In C++, proper input validation prevents crashes, incorrect results, and security vulnerabilities. It ensures your program behaves predictably even when given bad or unexpected input.

What Is Input Validation?

Input validation means checking the data entered by the user to confirm it matches the required type, format, and range. For example, if your program expects an integer, it should reject characters or symbols. If it expects a positive number, it should reject negative values.

Without input validation, the program may behave unpredictably, produce wrong outputs, or even crash.

Why Input Validation Is Important

  • Prevents runtime errors like division by zero or invalid memory access.

  • Improves program stability by handling unexpected user behavior.

  • Ensures data accuracy before performing calculations or storing data.

  • Protects against security risks such as code injection or buffer overflow.

Types of Input Validation

C++ input validation can be implemented in several ways, depending on what kind of data you expect:

  1. Type validation – Ensuring the user enters the correct data type (e.g., integer, float, string).

  2. Range validation – Checking if input values are within acceptable limits.

  3. Format validation – Making sure input follows a specific format (like an email address).

  4. Logical validation – Confirming that entered data makes sense logically.

Example: Basic Type Validation

When using cin for input, invalid data can cause problems if not handled properly.

Example:

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;

    if (cin.fail()) {
        cout << "Invalid input! Please enter a number.";
    } else {
        cout << "Your age is " << age << endl;
    }
    return 0;
}

Here, cin.fail() checks if the user entered something that cannot be stored in an integer variable.

Clearing Input Stream

When the user enters invalid data, the input stream (cin) goes into a failure state. You need to clear this state before reading new input.

Example:

#include <iostream>
using namespace std;

int main() {
    int number;
    while (true) {
        cout << "Enter an integer: ";
        cin >> number;

        if (cin.fail()) {
            cin.clear();              // Clear error flag
            cin.ignore(1000, '\n');   // Ignore invalid input
            cout << "Invalid input. Try again.\n";
        } else {
            cout << "You entered: " << number << endl;
            break;
        }
    }
    return 0;
}

This loop keeps asking until the user enters a valid integer.

Range Validation Example

You can ensure that the input is not only valid in type but also within a specific range.

Example:

#include <iostream>
using namespace std;

int main() {
    int marks;
    cout << "Enter marks (0-100): ";
    cin >> marks;

    if (cin.fail() || marks < 0 || marks > 100) {
        cout << "Invalid marks! Enter a number between 0 and 100.";
    } else {
        cout << "Marks entered: " << marks;
    }
    return 0;
}

This ensures the user enters marks only within the acceptable range.

Validating String Input

For string inputs, you can use conditions to check the format or length of the entered data.

Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    cout << "Enter your name: ";
    getline(cin, name);

    if (name.empty()) {
        cout << "Name cannot be empty.";
    } else {
        cout << "Welcome, " << name << "!";
    }
    return 0;
}

Here, an empty string input is rejected.

Validating Input Using Loops

You can use a loop to continuously ask for valid input until the user provides correct data.

Example:

#include <iostream>
using namespace std;

int main() {
    int age;

    while (true) {
        cout << "Enter your age: ";
        cin >> age;

        if (cin.fail() || age <= 0 || age > 120) {
            cin.clear();
            cin.ignore(1000, '\n');
            cout << "Please enter a valid age between 1 and 120.\n";
        } else {
            cout << "Age accepted: " << age << endl;
            break;
        }
    }
    return 0;
}

This method ensures that your program never proceeds with invalid input.

Combining Exception Handling with Input Validation

You can also use exceptions to handle invalid input in a more structured way.

Example:

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    int number;
    try {
        cout << "Enter a positive number: ";
        cin >> number;

        if (cin.fail())
            throw invalid_argument("Input must be a number.");
        if (number <= 0)
            throw out_of_range("Number must be positive.");

        cout << "Valid input: " << number;
    }
    catch (exception &e) {
        cout << "Error: " << e.what();
    }
    return 0;
}

This approach uses exceptions to cleanly separate normal logic from error handling.

Tips for Effective Input Validation

  • Always check both type and range of user input.

  • Use loops to re-prompt users when invalid data is entered.

  • Clear and ignore invalid input before taking new data.

  • Use exception handling for complex or critical input validation.

  • Avoid assuming the user will always enter correct data.

Summary of C++ Input Validation

Input validation is a key part of writing reliable and secure programs. It ensures that only correct, safe, and expected data is processed by your program. By checking type, range, and format, you can prevent crashes and unexpected behavior. Combining validation with exception handling gives you a solid, user-friendly approach to handling bad input in C++.


Practice Questions

  1. Write a C++ program that asks the user to enter an integer and keeps asking until a valid integer is entered.

  2. Create a program that accepts the user’s age and validates that it’s between 1 and 120.

  3. Build a program that takes a float number as input and checks if the user entered valid numeric data.

  4. Write a program that ensures the user inputs a non-empty string (no blank input allowed).

  5. Develop a program that accepts a phone number and validates that it contains exactly 10 digits.

  6. Write a C++ program that reads a single character and validates if it’s an alphabet letter only.

  7. Create a program that validates a user’s email address format (check for presence of ‘@’ and ‘.’).

  8. Write a program that accepts a password and validates it based on length and inclusion of digits and letters.

  9. Build a program that ensures a positive number is entered; throw and catch an exception if the input is negative.

  10. Write a menu-driven program where the user must select from valid menu options (1 to 5). If invalid, prompt again.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top