Input Validation in C++: Fix cin Errors and Reject Invalid Input
An age prompt should recover from abc and know whether 25abc is acceptable. Build a cin retry loop, trace its decisions, then replace it with strict whole-line validation.
KnowledgeGate Team
Exam prep & CS education

Your age prompt works for 25, but entering abc makes it repeat endlessly. Fixing this requires checking extraction, recovering the stream, and testing the allowed range. The same prompt also exposes 25abc, which needs a stronger check than successful integer extraction. The example accepts ages 1 through 120 inclusive, a chosen application rule rather than an official eligibility requirement.
What counts as valid input?
Valid input must satisfy three separate checks: conversion to an integer, membership in the allowed range, and absence of trailing non-whitespace text.
Input | Integer extraction | Range 1–120 | Whole-line rule |
|---|---|---|---|
| Succeeds | Passes | Passes |
| Fails | Not evaluated | Fails |
| Succeeds | Fails | Passes |
| Succeeds | Fails | Passes |
| Reads 25 | Passes | Fails: |
| Reads 25 | Passes | Fails: |
The policy accepts one age per line, permits surrounding whitespace, and rejects blank lines. The first program checks a numeric prefix and range; the later replacement enforces the complete policy.
Separating conversion from application rules is a useful programming habit to carry into the broader Coding & Skills resources.
Why cin stops reading after a failed extraction
int age{}; initialises an integer to zero. The expression if (!(std::cin >> age)) checks whether extraction failed; use age in application logic only after success.
Failure does not always preserve the old value. Since C++11, failed numeric conversion such as abc writes zero; an integer outside the representable range writes the nearest representable limit and sets failbit. Neither result is trustworthy after failure.
With abc\n, extraction sets failbit and leaves the offending text unread. Subsequent formatted reads cannot progress until recovery. As Microsoft Learn’s basic_ios reference defines them, fail() detects failbit or badbit, eof() reports an observed end of input, and bad() signals a serious I/O problem. EOF alone does not mean extraction failed.
The same stream-state ideas connect to types, conditions and loops in the C++ learning path.
Recover with clear(), ignore() and a retry loop
A C++11 retry loop handles recoverable extraction failures. It accepts 25abc as 25, because it discards the suffix. Whole-line validation comes later.
#include <iostream>
#include <limits>
int main() {
int age{};
for (;;) {
std::cout << "Age (1-120): ";
if (!(std::cin >> age)) {
if (std::cin.bad() || std::cin.eof()) {
std::cout << "Input ended or could not be read.\n";
return 0;
}
std::cin.clear();
std::cin.ignore(
std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter an integer.\n";
continue;
}
std::cin.ignore(
std::numeric_limits<std::streamsize>::max(), '\n');
if (age < 1 || age > 120) {
std::cout << "Use 1 to 120.\n";
continue;
}
std::cout << "Accepted: " << age << '\n';
break;
}
}After failed extraction, first stop for a serious error or end of input. Otherwise, clear the recoverable flags, discard through the newline, and retry. Clearing flags and removing characters are different operations; both are needed here.
numeric_limits<streamsize>::max() avoids an arbitrary discard length. The ignore() call consumes the newline too, as described in Microsoft Learn’s basic_istream reference. A successful extraction also discards the remainder of its line before the separate range check.
Trace abc, 150 and 25 through the loop

Submit exactly three lines: abc\n, 150\n, and 25\n. Here \n represents pressing Enter, not typing a backslash and the letter n.
Attempt | Input | Extraction result | Range decision | Action |
|---|---|---|---|---|
1 |
| Failure | Not evaluated | Clear, discard line, print “Enter an integer.” |
2 |
| Success: 150 | Reject | Discard newline, print “Use 1 to 120.” |
3 |
| Success: 25 | Accept | Discard newline, print “Accepted: 25” |
The first attempt never reaches the range condition. The second reaches it: 150 < 1 is false, but 150 > 120 is true, so rejection follows. No clear() is needed because conversion succeeded. For 25, both rejection comparisons are false. There are three prompts and no fourth attempt.

Reject 25abc with getline and istringstream
Whole-line validation uses getline and a fresh istringstream. getline reads the line; a fresh istringstream parses it. A local parsing failure does not poison std::cin.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string line;
while (std::cout << "Age (1-120): ", std::getline(std::cin, line)) {
std::istringstream parser(line);
int age{};
char extra{};
if (!(parser >> age) || (parser >> extra) ||
age < 1 || age > 120) {
std::cout << "Enter one whole number from 1 to 120.\n";
continue;
}
std::cout << "Accepted: " << age << '\n';
return 0;
}
std::cout << "Input ended or could not be read.\n";
}The comma in the while condition prints the prompt first, then uses getline's success as the loop condition.
After integer extraction, parser >> extra skips whitespace by default. Reading any extra character means rejection. Thus 25abc, 25.5, and 25 30 fail. Blank lines and abc fail integer extraction; integer overflow also fails without requiring a particular int width. Range checks reject 0 and 121; 25 is accepted as 25. End of input stops further reading.
If you also study input and output in C, remember that C's scanf/fgets and C++ streams have different recovery mechanisms.
Common traps and exam-style output checks
Calling clear() alone leaves abc waiting, so the next read fails again. Discard that line after clearing. Calling ignore() before clearing cannot reliably discard characters from a failed stream. Unconditionally clearing EOF causes endless retries; terminate when input has ended.
When mixing >> and getline, a pending newline can produce an empty first line. Finish the previous line deliberately, or use line-based input throughout. The simple >> loop skips empty or whitespace-only lines; the strict parser rejects them.
Use these output checks:
Does
25abcpass the first program? Yes, as 25. The suffix is discarded.Which validation rejects
150? The application range check. Integer conversion succeeds.
For a single valid 25 followed immediately by EOF, without a newline, integer extraction can still succeed. Use that value; do not reject it solely because eofbit is set. The Microsoft Learn references above explain these stream semantics.
Short version and the next practice step
Check extraction before using a value. Clear and discard recoverable bad input, check range separately, and parse whole lines to reject trailing junk.
Practise with quantity 1–10: reject 0, 11, and 3x; accept 1, 10, and 3 . Test each valid case in a fresh run because acceptance exits. Rename age to quantity and update all three places: the condition (quantity < 1 || quantity > 10), prompt, and error message.
For broader coding practice across languages, the Coding for Placements course is an optional next step.
Keep learning
HTML Forms Explained: Input Types, Validation Attributes, and the MCQs That Test Them
Build one registration form, trace its submitted data, and learn the input and validation details that HTML MCQs and frontend interviews repeatedly test.
C Fundamentals Mistakes: Fix 11 Data-Type, Operator and Flowchart Errors
Short C expressions can hide strict rules. Diagnose and repair 11 common errors involving initialisation, conversions, operators, increments and flowcharts.
Bottom-Up Parsing Mistakes for GATE: Fix Errors That Cost Marks
Prevent the small LR parsing errors that spoil an otherwise correct solution. Trace two examples and use a final check for handles, states, GOTO, closure and acceptance.
Infosys Mock Analysis: Fix Puzzle, Pseudocode and Verbal Errors
Do more than record a mock total. Preserve each error, find its primary cause, repair puzzle, pseudocode and verbal losses differently, then retest.





