C++20 sections · 1024 units
Open in Course

Reading Until EOF

Processing all input

I use while (cin >> x) to read until input ends: int x; while (cin >> x) { sum += x; } processes all integers until end-of-file or invalid input. On the terminal, users signal EOF by typing Ctrl+D (Linux/Mac) or Ctrl+Z (Windows).

When reading from a file with redirection, EOF occurs naturally when the file ends. This pattern combines reading and checking: while (cin >> x) attempts to read, and if it succeeds, the loop body runs.

If it fails, the loop exits. No separate check needed.