A C++ tool reading integers with std::cin >> n loops forever when the user types a letter; why, and how do you recover the stream?
answer
- the stream remembers it failed
- the bad characters are still there
- every later read gives up at once
- reset the flags, then discard
- end of input is different
basics
~20 sThe failed extraction sets failbit and leaves the letter in the input, so every later >> fails immediately without reading. Test the extraction itself, then call std::cin.clear() and std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n') to skip the bad line.
solid answer
~40 sWhen `std::cin >> n` meets a character that cannot start an `int`, the extraction stores `0` in `n` (since C++11), sets `failbit`, and leaves the offending characters in the input buffer. From then on every formatted input operation checks the stream state first and fails at once, so a loop that retries without changing anything spins forever and never sees new input. The fix has three parts. Test the read itself, as in `if (std::cin >> n)`, because a stream converts to `false` when `fail()` is true. Distinguish end of input with `eof()` and stop there. Otherwise call `std::cin.clear()` to reset the state, then `std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')` to throw away the rest of the bad line. The order matters: `ignore` does nothing on a stream that is still failed.
code
cpp · 18 lines#include <iostream>
#include <limits>
int main() {
long long sum = 0;
int n = -1;
while (true) {
if (std::cin >> n) {
sum += n;
continue;
}
if (std::cin.eof()) break; // clean end of input
std::cout << "skipping bad token, n is now " << n << '\n';
std::cin.clear(); // reset failbit first
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "sum = " << sum << '\n';
}go deeper
Recall that a failed read leaves std::cin in a failed state and that you test the read with if (std::cin >> n).
Explain the flags, that the bad characters stay in the buffer, the clear-then-ignore order, and the zero stored on failure.
Design input handling that separates end of input from bad input, and parse lines with getline plus istringstream when one bad token must not cost the rest.
Decide where a tool validates input and whether streams should throw, weighing user-facing recovery against fail-fast batch processing.
## The four state flags Every stream carries an `iostate` made of three bits, and `good()` means none is set: | Flag | Set when | Query | |---|---|---| | `eofbit` | an operation hit the end of the input | `eof()` | | `failbit` | an operation could not produce a value, such as letters where an `int` was expected | `fail()` (true for `failbit` or `badbit`) | | `badbit` | the stream buffer itself failed, such as a read error | `bad()` | | none | everything succeeded so far | `good()` | A stream used as a condition calls `explicit operator bool`, which returns `!fail()`. That is why `if (std::cin >> n)` and `while (std::cin >> n)` work: `>>` returns the stream, and the stream tests its own state. ## What happens on bad input Suppose the tool reads with this loop and the user types `abc`: ```cpp int n; while (!(std::cin >> n)) { std::cout << "not a number, try again\n"; } ``` 1. The extraction looks at `a`, cannot parse an integer, stores `0` in `n` and sets `failbit`. Before C++11, `n` was left unchanged; since C++11 the standard stores zero when nothing could be converted. 2. The characters `abc` are **not consumed**. They are still the next thing in the input. 3. The next `>>` constructs its **sentry**, sees that the stream is not good, sets `failbit` again and returns without reading anything. 4. The loop condition is still true, so it prints the message forever, without ever waiting for the user. A value that is too large has its own rule: `99999999999` read into an `int` stores the largest `int` and sets `failbit`. ## The recovery recipe ```cpp if (std::cin >> n) { /* use n */ } else if (std::cin.eof()) { /* no more input: stop */ } else { std::cin.clear(); // 1. reset the state std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 2. drop the bad line } ``` - **`clear()` first.** `ignore` is an input operation too; on a failed stream its sentry fails and nothing is discarded. - **`ignore(max, '\n')`** extracts and throws away characters up to and including the next newline. Passing `std::numeric_limits<std::streamsize>::max()` is special-cased by the standard to mean "no count limit". - **Check `eof()` before recovering.** At end of input, `clear()` and retry would loop forever too, because there is nothing left to read. Piped or redirected input ends this way, and so does a terminal when the user signals end of file (Ctrl-D on Unix-like systems). ## Consequences to explain in an interview - `ignore` to the newline discards everything left on that line, valid numbers included. With input `abc 5`, the `5` is thrown away. If you need token-level recovery, read the line with `std::getline` and parse it with a `std::istringstream`, where one bad token cannot poison `std::cin`. - `n` is `0` after a failed read, not its old value. Code that prints `n` in the error path shows `0`, which confuses users. - `badbit` is different: it means the stream is broken, and `clear()` plus retry is rarely the right answer. - Streams can be told to throw instead: `std::cin.exceptions(std::ios::failbit)` makes a failed extraction throw `std::ios_base::failure`. Few codebases do this for console input, because a typo is not exceptional. ## A robust reading loop ```cpp long long sum = 0; int n; while (true) { if (std::cin >> n) { sum += n; continue; } if (std::cin.eof()) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } ``` Given `10 20`, `abc 5` and `30` on three lines, it sums to 60: the bad line is skipped as a whole, including its `5`. ## Reading lines first, then parsing Many production tools avoid recovering `std::cin` at all. They read whole lines with `std::getline(std::cin, line)`, which only fails at end of input or on a device error, and then parse each line separately: - a `std::istringstream` over the line gives the same `>>` syntax, and a bad token only fails that temporary stream; - `std::from_chars` from `<charconv>` (C++17) converts without streams, exceptions or locales and reports exactly where parsing stopped. The console stream then never enters a failed state because of user typos, and the error message can quote the whole offending line, which users find far easier to fix than a silent skip.
- Why must clear() come before ignore()?`ignore` is an unformatted input function that starts by constructing a sentry. On a stream whose state is not good, the sentry fails and `ignore` extracts nothing. Calling `clear()` first resets the state so `ignore` can actually discard the bad characters.
- What value does n hold after std::cin >> n fails on "abc", and after it reads 99999999999?Since C++11, a failed conversion stores `0`, and `failbit` is set. A value too large for `int` stores the largest representable `int`, here 2147483647, and also sets `failbit`. Either way the stream must be cleared before the next read.
- std::cin skips the bad characters automatically on the next read
- Calling ignore() alone, without clear(), recovers the stream
- n keeps its previous value after a failed extraction
- eof() is the right test for whether the last read succeeded
- clear() also discards the characters that caused the failure