C++20 sections · 1024 units
Open in Course

Common Input Patterns

Reading unknown quantity

Real programs often need to read an unknown number of inputs. I use patterns: reading until end-of-file, reading until a sentinel value, or reading a count first then that many values.

The count-first pattern: int n; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; /* process x */ } works when the input format specifies how many values follow. This pattern appears in programming and file processing.

If the first line is 5, you know exactly 5 values follow. If cin >> n fails, you detect it before the loop starts.