← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 4 of 17

C++ Input Validation

Input validation checks that data entered by a user, such as through cin, actually matches what the program expects, using cin.fail() and cin.clear()/cin.ignore() to recover from invalid input.

Why Validate Input?

User input can never be fully trusted, since a person might type letters where a number is expected or leave a field empty, and unvalidated input can crash a program or silently produce wrong results.

Example: Why Validate Input?

cpp
#include <iostream>
#include <sstream>

int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	std::cout << "Extraction failed: " << input.fail() << std::endl;
	return 0;
}

Detecting Failed Input with cin.fail()

cin.fail() returns true if the most recent extraction operation failed, such as when non-numeric text was entered where a number was expected, letting the program detect and react to bad input.

Example: Detecting Failed Input with cin.fail()

cpp
#include <iostream>
#include <sstream>

int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	if (input.fail()) {
		std::cout << "Invalid input detected" << std::endl;
	}
	return 0;
}

Clearing the Error State with cin.clear()

Once cin enters a failed state, it stops processing further input until cin.clear() resets its internal error flags, which is a required step before the stream can be used again.

Example: Clearing the Error State with cin.clear()

cpp
#include <iostream>
#include <sstream>

int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	if (input.fail()) {
		input.clear();
		std::cout << "Cleared error state" << std::endl;
	}
	return 0;
}

Discarding Bad Input with cin.ignore()

After a failed read, the invalid characters typically remain in the input buffer, and cin.ignore() discards them (often up to the next newline) so the next read attempt starts fresh.

Example: Discarding Bad Input with cin.ignore()

cpp
#include <iostream>
#include <sstream>
#include <limits>

int main() {
	std::istringstream input("abc 42");
	int number;
	input >> number;
	input.clear();
	input.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
	input >> number;
	std::cout << number << std::endl;
	return 0;
}

A Complete Validation Loop

Combining a loop with cin.fail(), cin.clear(), and cin.ignore() creates a robust pattern that keeps re-prompting the user until genuinely valid input is provided.

Example: A Complete Validation Loop

cpp
#include <iostream>
#include <sstream>

int main() {
	std::istringstream input("abc 42");
	int number;
	while (!(input >> number)) {
		input.clear();
		input.ignore();
	}
	std::cout << "Valid input: " << number << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.