C++ Input Validation
In this page:
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?
// 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;
}
Login to try C/C++/Java/PHP code in the editor
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()
// 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;
}
Login to try C/C++/Java/PHP code in the editor
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()
// 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;
}
Login to try C/C++/Java/PHP code in the editor
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()
// 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;
}
Login to try C/C++/Java/PHP code in the editor
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
// 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;
}
Login to try C/C++/Java/PHP code in the editor
- Not calling
cin.clear()after bad input, so the stream stays in a failed state and later reads all fail. - Calling
cin.clear()but notcin.ignore(), so the bad text stays in the buffer and the loop repeats forever. - Assuming
cin >> xalways succeeds without checking its result.
Chapter Quiz — Complete all 17 topics to unlock
0/17 topics done
Complete these topics first:
- C++ vs C Differences
- C++ Interview Questions
- C++ Debugging Techniques
- C++ Input Validation
- C++ Namespaces
- C++ Header Files
- C++ Multi-file Programming
- C++ static_cast
- C++ dynamic_cast
- C++ const_cast
- C++ reinterpret_cast
- C++ Threads (std::thread)
- C++ Mutex & Locks
- C++ async & future
- C++ Mini Project — Calculator
- C++ Mini Project — Student Management
- C++ Interview Questions Advanced