C++ Input Validation

C++ Input Validation

When accepting input from a user via cin, you can never guarantee that they will type exactly what you expect. A robust C++ program must check if the input is valid before attempting to process it. This is called Input Validation.

If your program asks for a number, but the user types "Hello", cin will fail, causing unexpected behavior or an infinite loop in your program.


The Problem with cin

Let's look at what happens when cin expects an integer but receives a string.

Bad Input Problem

#include <iostream>
using namespace std;

int main() { int userAge; cout << "Please enter your age: "; cin >> userAge; // If the user types "Ten", cin enters a fail state!

cout << "You entered: " << userAge; return 0; }

When cin fails, it enters an error state. Until you manually clear that error state, cin will ignore all future input attempts!


Fixing Input with cin.fail(), cin.clear(), and cin.ignore()

To safely validate input, we need to utilize a few special cin functions:

  1. cin.fail(): Returns true if the last input operation failed (e.g., wrong data type).
  2. cin.clear(): Clears the error state of cin so it can start accepting input again.
  3. cin.ignore(): Discards the bad characters that are stuck in the input buffer.

Let's build a loop that safely forces the user to enter a valid number.

Proper Input Validation

#include <iostream>
#include <limits> // Needed for numeric_limits
using namespace std;

int main() { int userAge;

while (true) { cout << "Please enter your age (numbers only): "; cin >> userAge; if (cin.fail()) { cout << "Error: That was not a valid number. Try again.\n"; // 1. Clear the error state cin.clear(); // 2. Ignore the bad input remaining in the buffer cin.ignore(numeric_limits<streamsize>::max(), '\n'); } else { // Input was successful! Break out of the loop. break; } }

cout << "Awesome! You are " << userAge << " years old."; return 0; }

This standard loop ensures your program will never crash due to bad user input, resulting in professional and bug-free code.


Exercise

?

Which function is used to reset cin after it enters an error state?