← 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.
Syntax
cpp
if (std::cin.fail()) {
    std::cin.clear();                     // reset error flags
    std::cin.ignore(10000, '\n');         // discard bad 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 std::cout and std::cin
#include <iostream>
// Include string streams
#include <sstream>

// Program execution starts in main()
int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	// Print to the console with cout
	std::cout << "Extraction failed: " << input.fail() << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
// Include string streams
#include <sstream>

// Program execution starts in main()
int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	// Check whether input.fail()
	if (input.fail()) {
		// Print to the console with cout
		std::cout << "Invalid input detected" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
// Include string streams
#include <sstream>

// Program execution starts in main()
int main() {
	std::istringstream input("abc");
	int number;
	input >> number;
	// Check whether input.fail()
	if (input.fail()) {
		input.clear();
		// Print to the console with cout
		std::cout << "Cleared error state" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
// Include string streams
#include <sstream>
#include <limits>

// Program execution starts in main()
int main() {
	std::istringstream input("abc 42");
	int number;
	input >> number;
	input.clear();
	input.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
	input >> number;
	// Print to the console with cout
	std::cout << number << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>
// Include string streams
#include <sstream>

// Program execution starts in main()
int main() {
	std::istringstream input("abc 42");
	int number;
	// Repeat while !(input >> number) is true
	while (!(input >> number)) {
		input.clear();
		input.ignore();
	}
	// Print to the console with cout
	std::cout << "Valid input: " << number << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not calling cin.clear() after bad input, so the stream stays in a failed state and later reads all fail.
  2. Calling cin.clear() but not cin.ignore(), so the bad text stays in the buffer and the loop repeats forever.
  3. Assuming cin >> x always succeeds without checking its result.

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.