C++ Module 1 – Start here: toolchains, compiling and first programs
Console I/O in C++: cin, cout, print and println
Read numbers and whole lines with std::cin and std::getline, format output with C++23 std::print and std::println, and handle bad input and its end.
What you will learn
- Read numbers and whole lines from standard input
- Format output with std::print and std::println
- Avoid the getline-after-cin trap and detect bad input
- Choose standard output or standard error for each message, and '\n' or std::endl for each line
Before you start
What you’ll learn · Before you start
What you will learn
- Read numbers and whole lines from standard input
- Format output with std::print and std::println
- Avoid the getline-after-cin trap and detect bad input
- Choose standard output or standard error for each message, and '\n' or std::endl for each line
Before you start
On this page
A program read an age and then a full name from two lines of input, 19 and Asha Rao, and printed
Hello, [], age 19: the name came out empty. Console input and output in C++ is quick to start with and has a few
traps like this one, each easy to avoid once you have seen it happen. Use std::cin >> x to read numbers and words,
std::getline to read a whole line, and std::println for output that needs columns or a fixed number of decimals.
Every program below was built with both compilers and given the same input each time. You will step through the
reads one at a time, print a scorecard in aligned columns, and fix the two classic input bugs: the empty line after
>>, and input that is not a number.
A console program reads one stream and writes two
A console program talks through three standard streams: The three channels a console program starts with: standard input, which std::cin reads, and standard output and standard error, which std::cout and std::cerr write. The shell can connect each one to the terminal, a file or a pipe.: it reads standard input,
writes results to standard output and writes problems to standard error. In C++, std::cin reads standard
input, std::cout writes standard output and std::cerr writes standard error, all from <iostream>.
Run from a terminal, all three are the terminal: you type the input, and both kinds of output appear on the screen.
The shell can connect each stream elsewhere when it starts the program: < over.txt makes a file the standard input,
as online judges do, > result.txt sends standard output to a file, and 2> errors.txt does the same for standard
error. The diagram shows the three streams, the C++ names that use them, and where the shell can connect each one:
The three standard streams and the C++ names for them
Text description of the diagram
The diagram runs from top to bottom.
- Standard input comes from the keyboard, or from a file or a pipe that the shell connects with < or |. The program reads it with std::cin >> and std::getline.
- The program writes its results with std::cout, std::print or std::println, which go to standard output: the screen, or a file or a pipe connected with > or |.
- It writes error messages with std::cerr or std::println(stderr, ...), which go to standard error: the screen, or a file connected with 2>.
A dashed arrow from std::cin to std::cout says that std::cin flushes std::cout before it waits for input, so a prompt written with std::cout is always visible first.
Keeping the two outputs apart pays off as soon as the output is saved or read by another program, as the last program
of this lesson shows. The dashed arrow, from std::cin to std::cout, comes back in the section on whole lines.
Checkpoint
Check: The three standard streams
std::println formats a whole line in one call
C++23 adds std::print and std::println in <print>, which write formatted text in one call, the way Python’s
f-strings or C’s printf do.
std::cout << writes each value in turn. std::println takes a format string with {} where the values go, and ends
the line for you; std::print does not add the line break:
#include <iostream>
#include <print>
int main() {
const int runs = 74;
const int balls = 51;
std::cout << "Asha scored " << runs << " off " << balls << " balls\n";
std::println("Asha scored {} off {} balls", runs, balls);
std::print("Strike rate: {:.2f}", 100.0 * runs / balls);
std::print("\n");
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra two_ways.cpp -o two_ways && ./two_ways
g++-16 -std=c++23 -Wall -Wextra two_ways.cpp -o two_ways && ./two_ways
""") Output
$ clang++ -std=c++23 -Wall -Wextra two_ways.cpp -o two_ways && ./two_ways Asha scored 74 off 51 balls Asha scored 74 off 51 balls Strike rate: 145.10 $ g++-16 -std=c++23 -Wall -Wextra two_ways.cpp -o two_ways && ./two_ways Asha scored 74 off 51 balls Asha scored 74 off 51 balls Strike rate: 145.10
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 two_ways_session.py
The first two lines came out the same: Asha scored 74 off 51 balls. The third shows why a format string helps:
{:.2f} printed the strike rate as 145.10, with two decimals, in one short expression. With std::cout the same
result needs std::fixed and std::setprecision(2) (the second from <iomanip>), and both stay set for every later
number.
All three write to standard output, and this program mixes them: with both compilers, the lines came out in the order the program wrote them.
Checkpoint
Check: std::print and std::println
std::endl flushes every line, and a million flushes take seconds
To end a line, write '\n'. std::endl writes the line break and then flush: To force the text a stream is holding in its buffer out to the screen or the file at once. std::endl flushes after its line break; '\n' alone does not, so the stream can write many lines together. the stream,
which forces the text out to the screen or the file at once, and that costs time when it happens on every line:
#include <chrono>
#include <fstream>
#include <iostream>
int main() {
using clock = std::chrono::steady_clock;
const int lines = 1'000'000;
auto start = clock::now();
{
std::ofstream out("newline.txt");
for (int i = 0; i < lines; ++i) out << i << '\n';
}
auto newline_ms = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count();
start = clock::now();
{
std::ofstream out("endl.txt");
for (int i = 0; i < lines; ++i) out << i << std::endl;
}
auto endl_ms = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count();
std::cout << "'\\n': " << newline_ms << " ms\n";
std::cout << "std::endl: " << endl_ms << " ms\n";
} from session import run
# Both builds are optimised (-O2); the times differ from run to run.
run("""
clang++ -std=c++23 -O2 endl_cost.cpp -o endl_cost && ./endl_cost
g++-16 -std=c++23 -O2 endl_cost.cpp -o endl_cost && ./endl_cost
""") Output
$ clang++ -std=c++23 -O2 endl_cost.cpp -o endl_cost && ./endl_cost '\n': 114 ms std::endl: 5296 ms $ g++-16 -std=c++23 -O2 endl_cost.cpp -o endl_cost && ./endl_cost '\n': 79 ms std::endl: 5097 ms
This output changes from run to run: the times differ from run to run and from one computer to another
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 endl_session.py
The times change with the load on the machine. Over repeated runs on this track’s build machine, an Apple M5 Pro, the
million lines took 20 to 190 ms with '\n' and 1.1 to 5.9 seconds with std::endl, 25 to 65 times as long, with
both compilers; the run recorded above is one of them. Flush only when the text must appear right now, such as a
progress message, and use '\n' everywhere else.
Step through the two loops of the program and watch when the text actually reaches the file:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Lines collect. The first loop writes
out << i << '\n'. Each line goes into the stream's buffer, in memory, and nothing reaches the file yet. - Written together. Only when the buffer is full, or the file is closed at the end of the loop, does the stream write the waiting lines out, many at once.
- Fast. A million lines this way took 20 to 190 ms over repeated runs on this track's build machine, with either compiler.
- Every line flushed. The second loop writes
out << i << std::endl. std::endl ends the line and then flushes: it forces the waiting text out to the file at once. - One write per line. So the stream writes to the file after every single line: a million lines, a million writes, each one a request to the operating system.
- Slow. The same million lines took 1.1 to 5.9 seconds this way, 25 to 65 times as long as with '\n'. Flush only when the text must appear at once.
Key idea
End lines with '\n'. std::endl adds a flush to every line, and a million flushes made the same output 25 to 65
times slower.
Checkpoint
Check: std::endl and flushing
A format specification sets width, alignment, precision and base
A replacement field: A pair of braces in the format string of std::print or std::println, such as {} or {:.2f}. It is replaced by the next value, or by the value its number names, as in {0}. {} takes the next value; what goes after a colon inside it,
the format specification: The part of a replacement field after its colon, such as >8.2f in {:>8.2f}. It sets the fill character, the alignment, the width, the precision and the type of the value printed., sets its width, alignment, precision and base:
#include <print>
int main() {
const double pi = 3.14159265;
std::println("[{}]", pi);
std::println("[{:.2f}]", pi);
std::println("[{:8.3f}]", pi);
std::println("[{:<8}] [{:>8}] [{:^8}]", "left", "right", "centre");
std::println("[{:*^12}]", "four");
std::println("[{:+d}] [{:05d}] [{:#x}] [{:b}]", 42, 42, 255, 5);
std::println("{0} and {1}, then {0} again", "first", "second");
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra format_specs.cpp -o format_specs && ./format_specs
g++-16 -std=c++23 -Wall -Wextra format_specs.cpp -o format_specs && ./format_specs
""") Output
$ clang++ -std=c++23 -Wall -Wextra format_specs.cpp -o format_specs && ./format_specs [3.14159265] [3.14] [ 3.142] [left ] [ right] [ centre ] [****four****] [+42] [00042] [0xff] [101] first and second, then first again $ g++-16 -std=c++23 -Wall -Wextra format_specs.cpp -o format_specs && ./format_specs [3.14159265] [3.14] [ 3.142] [left ] [ right] [ centre ] [****four****] [+42] [00042] [0xff] [101] first and second, then first again
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 format_session.py
| Field | Printed (between the brackets) | What it does |
|---|---|---|
{} |
[3.14159265] |
The value in its shortest exact form |
{:.2f} |
[3.14] |
Two digits after the decimal point |
{:8.3f} |
[ 3.142] |
At least 8 characters wide; numbers are right-aligned |
{:<8}, {:>8}, {:^8} |
[left ], [ right], [ centre ] |
Left, right or centre within 8 characters |
{:*^12} |
[****four****] |
Centred, padded with * instead of spaces |
{:+d}, {:05d} |
[+42], [00042] |
Always show the sign; pad with zeros to 5 digits |
{:#x}, {:b} |
[0xff], [101] |
Hexadecimal with its prefix; binary |
{0}, {1} |
first and second, then first again |
Values by position, so one can be used twice |
Widths are what make tables line up. This scorecard sets each column’s width once, in the format string:
#include <print>
#include <string>
#include <vector>
struct Innings {
std::string batter;
int runs;
int balls;
int fours;
int sixes;
};
int main() {
const std::vector<Innings> card{
{"Asha", 74, 51, 8, 2},
{"Ravi", 9, 14, 1, 0},
{"Meera", 103, 88, 11, 3},
{"Kabir", 0, 2, 0, 0},
{"Zoya", 28, 19, 2, 2},
};
std::println("{:<8}{:>5}{:>6}{:>4}{:>4}{:>8}", "Batter", "R", "B", "4s", "6s", "SR");
int total = 0;
for (const auto& in : card) {
const double strike_rate = 100.0 * in.runs / in.balls;
std::println("{:<8}{:>5}{:>6}{:>4}{:>4}{:>8.2f}", in.batter, in.runs, in.balls, in.fours, in.sixes, strike_rate);
total += in.runs;
}
std::print("{:-<35}\n", "");
std::println("{:<8}{:>5}", "Total", total);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra scorecard.cpp -o scorecard && ./scorecard
g++-16 -std=c++23 -Wall -Wextra scorecard.cpp -o scorecard && ./scorecard
""") Output
$ clang++ -std=c++23 -Wall -Wextra scorecard.cpp -o scorecard && ./scorecard Batter R B 4s 6s SR Asha 74 51 8 2 145.10 Ravi 9 14 1 0 64.29 Meera 103 88 11 3 117.05 Kabir 0 2 0 0 0.00 Zoya 28 19 2 2 147.37 ----------------------------------- Total 214 $ g++-16 -std=c++23 -Wall -Wextra scorecard.cpp -o scorecard && ./scorecard Batter R B 4s 6s SR Asha 74 51 8 2 145.10 Ravi 9 14 1 0 64.29 Meera 103 88 11 3 117.05 Kabir 0 2 0 0 0.00 Zoya 28 19 2 2 147.37 ----------------------------------- Total 214
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 scorecard_session.py
The batter’s name is left-aligned in 8 characters ({:<8}) and every number is right-aligned in its own column, so the
strike rates 145.10, 64.29, 117.05, 0.00 and 147.37 end in the same column. The line of dashes is
{:-<35} with an empty value: 35 characters of fill. If a value is wider than its field, it is printed in full and
pushes the rest of the line to the right, so choose widths for the longest value you expect.
Step through Asha’s row, one field at a time, and count the characters each one takes:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- Left in 8.
{:<8}takes the first value, the nameAsha, and left-aligns it in 8 characters:Ashaand then 4 spaces. - Right in 5.
{:>5}right-aligns the runs, 74, in 5 characters, so 3 spaces come first. Numbers line up on their last digit this way. - Right in 6.
{:>6}puts the balls, 51, at the right of 6 characters, after 4 spaces. - Two narrow columns. The fours and the sixes get 4 characters each: 3 spaces and then
8, 3 spaces and then2. - Two decimals in 8.
{:>8.2f}prints the strike rate with two digits after the point,145.10, right-aligned in 8 characters, after 2 spaces. - The whole row. The widths add up to 35 characters, 8 + 5 + 6 + 4 + 4 + 8, and every row uses the same format string, so every column lines up. That is why the line of dashes is 35 long.
Text beyond English on Windows
std::print writes to the console through the operating system’s Unicode interface when the program’s text is
UTF-8, so characters such as é or € and text in scripts such as Devanagari or Tamil appear correctly in the Windows
console, which output through std::cout often does not. With Microsoft’s compiler, build with /utf-8 so that the
program’s string literals are UTF-8 (/utf-8 sets both the source and the execution character set). Most macOS and
Linux terminals use UTF-8 already.
Checkpoint
Check: Width, alignment, precision and base
std::cin skips whitespace, then reads what fits the type
std::cin >> x skips any spaces, tabs and line breaks, then reads as many characters as fit the type of x: digits
for an int, one word for a std::string. Several reads can be chained (std::cin >> a >> b), and it makes no
difference whether the values are on one line or several. Used as a condition, a read is true while it succeeds, so a
loop can read everything up to the end of the input:
#include <iostream>
#include <print>
int main() {
int runs = 0;
int total = 0;
int balls = 0;
while (std::cin >> runs) {
total += runs;
++balls;
}
std::println("{} runs off {} balls", total, balls);
} from session import run
run("""
cat over.txt
clang++ -std=c++23 -Wall -Wextra sum_runs.cpp -o sum_runs && ./sum_runs < over.txt
g++-16 -std=c++23 -Wall -Wextra sum_runs.cpp -o sum_runs && ./sum_runs < over.txt
""") Output
$ cat over.txt 1 4 0 6 2 1 $ clang++ -std=c++23 -Wall -Wextra sum_runs.cpp -o sum_runs && ./sum_runs < over.txt 14 runs off 6 balls $ g++-16 -std=c++23 -Wall -Wextra sum_runs.cpp -o sum_runs && ./sum_runs < over.txt 14 runs off 6 balls
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sum_runs_session.py
The input 1 4 0, 6 2 and 1 spread over three lines gave 14 runs off 6 balls. The loop stops at the end of the
input, and it would also stop at the first word that is not a number. To end input typed at the keyboard, press
Ctrl-D (macOS and Linux) or Ctrl-Z and then Enter (Windows). To give a program a file as its input, as online judges
do, run ./sum_runs < over.txt.
Step through the six reads of that run, and the seventh, which ends the loop:
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- Read 1.
std::cin >> runsreads1, the first number of line 1. The read worked, so the loop body runs:totalis 1 andballsis 1. - Read 4. The next read skips the space after
1and takes4:totalis 5,ballsis 2. - Read 0. It skips the next space and takes
0, a ball with no run:totalstays 5,ballsis 3. - On to line 2. The line break after
0is skipped like any space, so the next read takes6from line 2:totalis 11,ballsis 4. - Read 2. Then
2:totalis 13,ballsis 5. - Read 1. Then the
1on line 3:totalis 14,ballsis 6. - The read fails. Nothing is left to read, so the next read fails. As a condition, a failed read is false, and the loop ends.
- The result. The program prints
14 runs off 6 balls, with both compilers. It made no difference that the numbers came on three lines.
Checkpoint
Check: Reading values with std::cin
std::getline after a number returns an empty line
std::getline(std::cin, line) reads everything up to the next line break, spaces included, and removes the line
break. That is how to read a full name. Mixed with >>, though, it fails in a way that surprises almost everyone:
#include <iostream>
#include <string>
int main() {
int age = 0;
std::string name;
std::cout << "Age: ";
std::cin >> age;
std::cout << "Full name: ";
std::getline(std::cin, name);
std::cout << "\nHello, [" << name << "], age " << age << '\n';
} The input was 19 on one line and Asha Rao on the next, yet the program printed Hello, [], age 19: an empty
name. std::cin >> age read 19 and stopped at the line break after it, leaving that line break waiting.
std::getline then read up to the first line break, which came straight away, and returned an empty line. The
square brackets in the output are there to make the empty string visible.
The fix is to skip the leftover whitespace before getline. std::ws does exactly that:
#include <iostream>
#include <string>
int main() {
int age = 0;
std::string name;
std::cout << "Age: ";
std::cin >> age;
std::cout << "Full name: ";
std::getline(std::cin >> std::ws, name);
std::cout << "\nHello, [" << name << "], age " << age << '\n';
} from session import run
# The same input file for both programs: an age on the first line, a full name on the second.
run("""
cat age_name.txt
clang++ -std=c++23 -Wall -Wextra age_then_name.cpp -o age_then_name && ./age_then_name < age_name.txt
g++-16 -std=c++23 -Wall -Wextra age_then_name.cpp -o age_then_name && ./age_then_name < age_name.txt
clang++ -std=c++23 -Wall -Wextra age_then_name_fixed.cpp -o age_then_name_fixed && ./age_then_name_fixed < age_name.txt
g++-16 -std=c++23 -Wall -Wextra age_then_name_fixed.cpp -o age_then_name_fixed && ./age_then_name_fixed < age_name.txt
""") Output
$ cat age_name.txt 19 Asha Rao $ clang++ -std=c++23 -Wall -Wextra age_then_name.cpp -o age_then_name && ./age_then_name < age_name.txt Age: Full name: Hello, [], age 19 $ g++-16 -std=c++23 -Wall -Wextra age_then_name.cpp -o age_then_name && ./age_then_name < age_name.txt Age: Full name: Hello, [], age 19 $ clang++ -std=c++23 -Wall -Wextra age_then_name_fixed.cpp -o age_then_name_fixed && ./age_then_name_fixed < age_name.txt Age: Full name: Hello, [Asha Rao], age 19 $ g++-16 -std=c++23 -Wall -Wextra age_then_name_fixed.cpp -o age_then_name_fixed && ./age_then_name_fixed < age_name.txt Age: Full name: Hello, [Asha Rao], age 19
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 age_session.py
std::getline(std::cin >> std::ws, name) printed Hello, [Asha Rao], age 19. std::ws also skips blank lines and
leading spaces, which is right for a name. If spaces at the start of a line matter, use
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after the >> instead, which throws away only
the rest of that one line.
Step through both programs on the same input, and follow the line break after 19:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- The age.
std::cin >> agereads19and stops at the line break after it, which it leaves in the input. - A line break waits. The line break after
19is now the next thing in the input, waiting for whatever reads next. - An empty line.
std::getline(std::cin, name)reads everything up to the next line break. The waiting one comes first, so it returns an empty line and removes that line break. - The name is never read. The program prints
Hello, [], age 19.Asha Raois still in the input when it ends. - The fixed program. The fixed program reads
std::getline(std::cin >> std::ws, name).std::wsfirst skips the waiting line break and any spaces, sogetlinestarts atAsha Rao.
Both programs print Age: Full name: on one line because the input came from a file, so nothing typed was echoed. In a
terminal, your typing appears after each prompt. A prompt written with std::cout always shows before the program
waits, because std::cin flushes std::cout before every read (the standard ties the two streams together).
A line read straight after a number
std::cin >> age; followed by std::getline(std::cin, name); gives an empty name, because getline reads the line
break that >> left behind. Write std::getline(std::cin >> std::ws, name); instead.
Checkpoint
Check: Whole lines and the getline trap
A failed read stores 0 and stops every read until clear()
When std::cin >> overs meets twenty, the read fails: overs is set to 0, the stream is marked as failed, and
twenty is left in the input. Every later read fails at once until the program deals with it. This loop asks until
it gets a number in range:
#include <iostream>
#include <limits>
#include <print>
int main() {
int overs = -1;
while (true) {
std::cout << "Overs (1-50): ";
if (std::cin >> overs && overs >= 1 && overs <= 50) {
break;
}
if (std::cin.eof()) {
std::println(stderr, "\nThe input ended before a valid number.");
return 1;
}
if (std::cin.fail()) {
std::println("\nNot a whole number (overs is now {}). Try again.", overs);
std::cin.clear();
} else {
std::println("\n{} is outside 1-50. Try again.", overs);
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::println("\nA {}-over match has {} balls per side.", overs, overs * 6);
} from session import run
# Built once with each compiler, then given two inputs: three answers, and a single wrong one.
run("""
clang++ -std=c++23 -Wall -Wextra read_overs.cpp -o read_overs && ./read_overs < overs.txt
./read_overs < overs_bad.txt
g++-16 -std=c++23 -Wall -Wextra read_overs.cpp -o read_overs && ./read_overs < overs.txt
./read_overs < overs_bad.txt
""") Output
$ clang++ -std=c++23 -Wall -Wextra read_overs.cpp -o read_overs && ./read_overs < overs.txt Overs (1-50): Not a whole number (overs is now 0). Try again. Overs (1-50): 75 is outside 1-50. Try again. Overs (1-50): A 20-over match has 120 balls per side. $ ./read_overs < overs_bad.txt Overs (1-50): Not a whole number (overs is now 0). Try again. Overs (1-50): The input ended before a valid number. [exit status 1] $ g++-16 -std=c++23 -Wall -Wextra read_overs.cpp -o read_overs && ./read_overs < overs.txt Overs (1-50): Not a whole number (overs is now 0). Try again. Overs (1-50): 75 is outside 1-50. Try again. Overs (1-50): A 20-over match has 120 balls per side. $ ./read_overs < overs_bad.txt Overs (1-50): Not a whole number (overs is now 0). Try again. Overs (1-50): The input ended before a valid number. [exit status 1]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 overs_session.py
With the input twenty, 75 and 20, it printed:
Not a whole number (overs is now 0). Try again., after whichstd::cin.clear()removed the failed state andstd::cin.ignore(…, '\n')threw away the rest of the bad line;75 is outside 1-50. Try again.: that read worked, so only the range check failed;A 20-over match has 120 balls per side.
With only ten on standard input, it printed the first message, then the input ended, so it wrote
The input ended before a valid number. to standard error and exited with status 1. Two mistakes make such loops
hang or spin forever: calling clear() without ignore(), which reads the same bad word again and again, and
forgetting the end-of-input check, after which every read fails at once.
Step through the program’s tests in their order, for each answer of both input files:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- twenty. The first answer is
twenty. The read fails:oversbecomes 0, the stream is marked as failed, andtwentystays in the input. - Not a number. The read did not work and the input has not ended, so the program prints
Not a whole number (overs is now 0). Try again.andclear()removes the failed state. - The bad line goes.
std::cin.ignore(…, '\n')throws away the rest of the bad line,twentyincluded, so the next read starts on the next line. - 75. The read of
75works, but 75 is outside 1 to 50. The program prints75 is outside 1-50. Try again., ignores the rest of the line and asks again. - 20.
20is a whole number from 1 to 50, so the loop ends, and the program printsA 20-over match has 120 balls per side. - ten, then nothing. Given only
ten, the program saysNot a whole numberand asks again. Now the input has ended, so it writesThe input ended before a valid number.to standard error and exits with status 1.
Write error messages to standard error, with std::cerr << or std::println(stderr, …), as this program does. They
then stay on the screen even when a user saves the normal output with ./read_overs > result.txt, and they never get
mixed into results that another program reads.
Key idea
After a failed read, clear() the stream and ignore() the rest of the line before you ask again, and stop when
eof() says the input has ended.
Checkpoint
Check: Input that is not a number
Exercise: a marks report
Read a count n and then n whole-number marks from standard input, and print their average with two decimals and
the highest mark. For the input 5, then 72 85 64 and 91 57 on two more lines, the output must be exactly
Average: 73.80 and then Highest: 91, each on its own line. If the input ends early or holds something that is not a
number, print a message to standard error and exit with status 1.
Hint: read the count first and check it, then read the marks in a for loop, and divide as double, not as int.
One solution
#include <iostream>
#include <print>
int main() {
int n = 0;
if (!(std::cin >> n) || n <= 0) {
std::println(stderr, "First give how many marks follow (at least 1).");
return 1;
}
int total = 0;
int highest = 0;
for (int i = 0; i < n; ++i) {
int mark = 0;
if (!(std::cin >> mark)) {
std::println(stderr, "Expected {} marks, got {}.", n, i);
return 1;
}
total += mark;
if (i == 0 || mark > highest) {
highest = mark;
}
}
std::println("Average: {:.2f}", static_cast<double>(total) / n);
std::println("Highest: {}", highest);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra -Wpedantic -Wconversion marks_report.cpp -o marks_report && ./marks_report < marks.txt
./marks_report < marks_short.txt
g++-16 -std=c++23 -Wall -Wextra -Wpedantic -Wconversion marks_report.cpp -o marks_report && ./marks_report < marks.txt
./marks_report < marks_short.txt
""") Output
$ clang++ -std=c++23 -Wall -Wextra -Wpedantic -Wconversion marks_report.cpp -o marks_report && ./marks_report < marks.txt Average: 73.80 Highest: 91 $ ./marks_report < marks_short.txt Expected 3 marks, got 2. [exit status 1] $ g++-16 -std=c++23 -Wall -Wextra -Wpedantic -Wconversion marks_report.cpp -o marks_report && ./marks_report < marks.txt Average: 73.80 Highest: 91 $ ./marks_report < marks_short.txt Expected 3 marks, got 2. [exit status 1]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 marks_session.py
It printed Average: 73.80 and Highest: 91. Given 3 and only two marks, it printed Expected 3 marks, got 2. to
standard error and exited with status 1.
Check yourself
When your report prints exactly those two lines, try the questions below. They start with the idea you have answered least well, move up a level after each right answer, and explain every choice:
Practice that adapts to you
Practise this lesson
15 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
What is the difference between std::endl and '\n'? (warm-up)
Both end the line. std::endl then also flushes the stream: the standard defines it as writing a newline followed by
a call to flush(). Flushing forces the buffered text out to the terminal or the file, which costs a system call, so
std::endl in a loop is slow: writing a million lines to a file took 1.1 to 5.9 seconds with std::endl against
20 to 190 ms with '\n' on this track’s build machine. Use '\n' by default and flush deliberately when the text must
appear at once, for example a progress line or output that an interactive judge reads before it sends more input.
std::cerr flushes after every write anyway, and std::cin flushes std::cout before reading.
An interviewer rarely stops at the first answer. Two follow-up questions come next: pick the answer you would give, and the feedback says what each choice gets right and where it falls short.
Checkpoint
Interview round: two follow-up questions
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A program reads a count with std::cin >> n, then n names with std::getline. On your machine every name is right. On the judge the first name is empty, and later names never compare equal to the expected strings. Explain both bugs and write the reading code you would trust.
-
Fresher to mid
You write a function that reads one integer from 1 to 100 from std::cin and asks again on bad input. When the user types abc and then ends the input, it loops forever. Explain why, fix it, and say what else a robust reader must handle.
Key takeaways
std::cin,std::coutandstd::cerr(from<iostream>) read standard input and write standard output and standard error; C++23’sstd::printandstd::println(from<print>) format output in one call.- Inside
{},:.2fsets the decimals,:<8,:>8and:^8the alignment and width, and:#xand:bthe base. - Use
'\n', notstd::endl, to end lines: flushing every line was 25 to 65 times slower when writing a file. std::cin >> xskips whitespace and stops at the first character that does not fit;while (std::cin >> x)reads to the end of the input.- After
>>, a line break is still waiting: read lines withstd::getline(std::cin >> std::ws, line). - A failed read sets the value to 0 and the stream to failed;
clear()it,ignore()the bad line, and checkeof()so the loop cannot spin.
Terms in this lesson
- flush
- To force the text a stream is holding in its buffer out to the screen or the file at once. std::endl flushes after its line break; '\n' alone does not, so the stream can write many lines together.
- format specification
- The part of a replacement field after its colon, such as >8.2f in {:>8.2f}. It sets the fill character, the alignment, the width, the precision and the type of the value printed.
- replacement field
- A pair of braces in the format string of std::print or std::println, such as {} or {:.2f}. It is replaced by the next value, or by the value its number names, as in {0}.
- standard streams
- The three channels a console program starts with: standard input, which std::cin reads, and standard output and standard error, which std::cout and std::cerr write. The shell can connect each one to the terminal, a file or a pipe.
Corrections
- The times for std::endl and '\n' now give the range of every run on the track's build machine, including the run shown with the example.
References
- P2093R14: Formatted output (ISO/IEC JTC1/SC22/WG21)
- Working Draft, Programming Languages: C++ (N4950) (ISO/IEC JTC1/SC22/WG21)
- /utf-8 (Set source and execution character sets to UTF-8) (Microsoft)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress