Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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

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:

Standard input flows through std::cin into the program, which writes to standard output and standard error.Keyboard,< file or | pipestd::cin >>std::getlineYour programstd::cout << ...std::print, std::printlnstd::cerr << ...std::println(stderr, ...)Standard outputscreen, > file or | pipeStandard errorscreen or 2> filestandard inputflushes before reading

The three standard streams and the C++ names for them

Text description of the diagram

The diagram runs from top to bottom.

  1. 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.
  2. 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 |.
  3. 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

  1. Question 1 of 2 Where should a program write the message The input ended before a valid number.?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: To standard error, with std::cerr or std::println(stderr, …)

    A console program reads standard input, writes results to standard output and writes problems to standard error. read_overs.cpp writes its message with std::println(stderr, …), so it shows even when the results go to a file.

  2. Question 2 of 2 An online judge runs your program as ./sum_runs < over.txt. What does < over.txt do?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It makes the file the program's standard input, so std::cin reads the file

    < file makes a file the standard input, > file sends standard output to a file, and 2> file does the same for standard error. The program itself is unchanged: sum_runs.cpp printed 14 runs off 6 balls from over.txt.

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:

std::cout, std::println and std::print C++ · two_ways.cpp
#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");
}
Built and run with both compilers Python · two_ways_session.py
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

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    std::print("Total: {}", 5);
    std::print("Wickets: {}", 2);
    Show the answer: Question 1 of 2

    Answer: Total: 5Wickets: 2, on one line

    std::println writes the formatted text followed by a line break; std::print writes only the text, so the next output continues on the same line. two_ways.cpp used std::print("\n") to end its last line.

  2. Question 2 of 2 Which header must a file include to use std::println?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: <print>

    C++23 adds std::print and std::println in <print>. They take a format string with {} where the values go, the way Python's f-strings or C's printf do.

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:

Writing a million lines to a file C++ · endl_cost.cpp
#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";
}
One run of each build Python · endl_session.py
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:

Interactive · message by message A million lines, with '\n' and with std::endl Step through the two loops of endl_cost.cpp. Watch when the text actually reaches the file.
A million lines, with '\n' and with std::endl, step 6 of 6. Messages so far: The program to The stream: 0, then 1, 2, 3 …; The stream to The file: many lines at once; The program to The stream: 0, then flush; The stream to The file: one line.The program1.1 to 5.9 sThe streamone line waitingThe fileendl.txt0, then 1, 2, 3 …many lines at once0, then flushone line

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. Fast. A million lines this way took 20 to 190 ms over repeated runs on this track's build machine, with either compiler.
  4. 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.
  5. 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.
  6. 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

  1. Question 1 of 2 What does std::endl write?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A line break, then a flush of the stream

    std::endl writes the line break and then flushes the stream, which forces the text out to the screen or the file at once. '\n' ends the line and lets the stream collect many lines before writing them together.

  2. Question 2 of 2 Which of these is a good place to flush on purpose?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A progress line, such as Reading file 3 of 10, before a long piece of work

    Flush only when the text must appear right now, such as a progress message, and use '\n' everywhere else. A read from std::cin flushes std::cout for you, and std::cerr flushes after every write.

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:

Width, alignment, precision and base C++ · format_specs.cpp
#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");
}
What each field printed Python · format_session.py
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:

An aligned batting scorecard C++ · scorecard.cpp
#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);
}
The scorecard, from both builds Python · scorecard_session.py
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:

Interactive · step by step Asha's row of the scorecard, field by field Step through the row's six fields. Each one takes the next value and fills a column of fixed width.
Asha's row of the scorecard, field by field, step 6 of 6. Showing {:<8} batter, {:>5} runs, {:>6} balls, {:>4} fours, {:>4} sixes, {:>8.2f} strike rate, Asha, 74, 51, 8, 2, 145.10.{:<8} batter{:>5} runs{:>6} balls{:>4} fours{:>4} sixes{:>8.2f} strike rateAshathen 4 spaces74after 3 spaces51after 4 spaces8after 3 spaces2after 3 spaces145.10after 2 spaces

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Left in 8. {:<8} takes the first value, the name Asha, and left-aligns it in 8 characters: Asha and then 4 spaces.
  2. 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.
  3. Right in 6. {:>6} puts the balls, 51, at the right of 6 characters, after 4 spaces.
  4. Two narrow columns. The fours and the sixes get 4 characters each: 3 spaces and then 8, 3 spaces and then 2.
  5. 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.
  6. 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

  1. Question 1 of 2 A batter's name is Shubhangi, nine characters, and the scorecard prints names with {:<8}. What happens to that row?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The name is printed in full, and the rest of the row moves one place to the right

    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.

  2. Question 2 of 2 Which replacement field prints the number 42 as 00042?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: {:05d}

    In the lesson's table, {:05d} printed [00042] and {:+d} printed [+42]. The fill character, the alignment and the width can be combined, as {:^12} did for [*four**].

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:

Reading numbers until the input ends C++ · sum_runs.cpp
#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);
}
Six balls from a file Python · sum_runs_session.py
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:

Interactive · step by step while (std::cin >> runs) reading over.txt Step through the reads. Each one skips spaces and line breaks, then takes the next whole number.
while (std::cin >> runs) reading over.txt, step 8 of 8. Showing line 1: 1 4 0, line 2: 6 2, line 3: 1, end of the input, runs (1), total (14), balls (6), what it prints (14 runs off 6 balls). In focus: what it prints, total, balls.line 1: 1 4 0line 2: 6 2line 3: 1end of the inputruns1total14balls6what it prints14 runs off 6 balls

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. Read 1. std::cin >> runs reads 1, the first number of line 1. The read worked, so the loop body runs: total is 1 and balls is 1.
  2. Read 4. The next read skips the space after 1 and takes 4: total is 5, balls is 2.
  3. Read 0. It skips the next space and takes 0, a ball with no run: total stays 5, balls is 3.
  4. On to line 2. The line break after 0 is skipped like any space, so the next read takes 6 from line 2: total is 11, balls is 4.
  5. Read 2. Then 2: total is 13, balls is 5.
  6. Read 1. Then the 1 on line 3: total is 14, balls is 6.
  7. 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.
  8. 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

  1. Question 1 of 2 A program runs std::string name; std::cin >> name; and the user types Asha Rao. What is in name?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Asha

    std::cin >> x skips 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.

  2. Question 2 of 2 When does the loop while (std::cin >> runs) stop?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: At the end of the input, or at the first word that is not a number

    Used as a condition, a read is true while it succeeds. With over.txt the loop read six numbers, and the seventh read failed at the end of the input.

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:

Age, then full name C++ · age_then_name.cpp
#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:

std::ws skips the leftover line break C++ · age_then_name_fixed.cpp
#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';
}
Both programs, both compilers, the same input Python · age_session.py
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:

Interactive · step by step Age, then full name, from age_name.txt Step through the reads of the program with the bug, then of the fixed one. Watch the line break after 19.
Age, then full name, from age_name.txt, step 5 of 5. Showing 19, line break (skipped by std::ws), Asha Rao, line break, age (19), name ([Asha Rao]), what it prints (Hello, [Asha Rao], age 19). In focus: Asha Rao, name.19line breakskipped by std::wsAsha Raoline breakage19name[Asha Rao]what it printsHello, [Asha Rao], age 19

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The age. std::cin >> age reads 19 and stops at the line break after it, which it leaves in the input.
  2. A line break waits. The line break after 19 is now the next thing in the input, waiting for whatever reads next.
  3. 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.
  4. The name is never read. The program prints Hello, [], age 19. Asha Rao is still in the input when it ends.
  5. The fixed program. The fixed program reads std::getline(std::cin >> std::ws, name). std::ws first skips the waiting line break and any spaces, so getline starts at Asha 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

  1. Question 1 of 2 After std::cin >> age;, which line reads the full name Asha Rao?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::getline(std::cin >> std::ws, name);

    std::cin >> age stops before the line break after 19. std::getline(std::cin >> std::ws, name) skips it, and any blank lines and leading spaces, then reads Asha Rao.

  2. Question 2 of 2 When is the lesson's std::cin.ignore(…, '\n') call, after the >>, better than std::ws?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: When spaces at the start of the next line matter, because std::ws would skip them

    std::ws skips all whitespace, which is right for a name. If the spaces at the start of the next line are part of the data, throw away only the rest of the current line with ignore instead.

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:

Asking until the answer is a valid number C++ · read_overs.cpp
#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);
}
Three answers, then one wrong answer and the end Python · overs_session.py
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 which std::cin.clear() removed the failed state and std::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:

Interactive · stage by stage Asking until the answer is a valid number Step through the program's tests for each answer of overs.txt, then for overs_bad.txt.
Asking until the answer is a valid number, step 6 of 6. Showing Print the prompt, Read: std::cin >> overs (ten, then the end), Worked and 1 to 50?, Input ended?, Read failed?, ignore() the rest, Print the balls. In focus: Input ended?.ask againyesPrint the promptOvers (1-50):Read: std::cin >> oversten, then the endWorked and 1 to 50?yes: leave the loopInput ended?yes: stderr, status 1Read failed?yes: clear(); no: rangeignore() the restof the line, ask againPrint the ballsovers times 6

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. twenty. The first answer is twenty. The read fails: overs becomes 0, the stream is marked as failed, and twenty stays in the input.
  2. 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. and clear() removes the failed state.
  3. The bad line goes. std::cin.ignore(…, '\n') throws away the rest of the bad line, twenty included, so the next read starts on the next line.
  4. 75. The read of 75 works, but 75 is outside 1 to 50. The program prints 75 is outside 1-50. Try again., ignores the rest of the line and asks again.
  5. 20. 20 is a whole number from 1 to 50, so the loop ends, and the program prints A 20-over match has 120 balls per side.
  6. ten, then nothing. Given only ten, the program says Not a whole number and asks again. Now the input has ended, so it writes The 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

  1. Question 1 of 2 A retry loop calls std::cin.clear() after a failed read, but never ignore(). The user typed twenty. What happens?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The next read meets twenty again and fails again, for ever

    Two mistakes make such loops hang or spin: calling clear() without ignore(), which reads the same bad word again and again, and forgetting the end-of-input check. read_overs.cpp avoids both.

  2. Question 2 of 2 Why does read_overs.cpp test std::cin.eof() before it tries again?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Once the input has ended, every read fails at once, so without the test the loop would never stop

    After the input ends, every read fails at once. Checking eof() first stops the loop with a clear message instead of letting it spin: The input ended before a valid 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.

Text Diff Paste your program's output and the expected output to see the exact character that differs, as a judge compares them.

One solution

A marks report with input checks C++ · marks_report.cpp
#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);
}
Five marks, then an input that ends early Python · marks_session.py
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.

  1. Question 1 of 15 Which of these writes to standard error?

    Choose one answer.

    Show the answer: Question 1 of 15

    Answer: std::cerr

    std::cin, std::cout and std::cerr come from <iostream>. std::print and std::println write standard output unless their first argument is stderr.

  2. Question 2 of 15 A user runs ./read_overs > result.txt, and the input ends before a valid number. Where does The input ended before a valid number. appear?

    Choose one answer.

    Show the answer: Question 2 of 15

    Answer: On the screen, because the program writes it to standard error

    Error messages written to standard error 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.

  3. Question 3 of 15 What is the difference between std::println("Total: {}", 5) and std::print("Total: {}", 5)?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: println ends the line after the text; print does not

    Both are C++23 functions from <print> and both use the same format strings. println writes the formatted text followed by a line break; print writes only the text, so the next output continues on the same line.

  4. Question 4 of 15 What does this print?

    Read the code, then choose one answer.

    std::println("{} off {} balls", 74, 51);
    Show the answer: Question 4 of 15

    Answer: 74 off 51 balls, then a line break

    The braces are filled with the values in order. two_ways.cpp printed Asha scored 74 off 51 balls this way, the same line std::cout printed piece by piece.

  5. Question 5 of 15 Why did writing a million lines with std::endl take 25 to 65 times as long as with '\n' in the lesson?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: std::endl flushes the stream after every line, forcing a write each time

    std::endl is a line break followed by flush(). Each flush sends the buffered text to the file at once, so a million lines cause a million writes, while '\n' lets the stream collect many lines and write them together.

  6. Question 6 of 15 What should end most lines of output?

    Choose one answer.

    Show the answer: Question 6 of 15

    Answer: '\n'

    To end a line, write '\n'. Use std::endl, or another flush, only where the text must appear right now, such as a progress message.

  7. Question 7 of 15 Which replacement field prints 3.14159 as 3.14?

    Choose one answer.

    Show the answer: Question 7 of 15

    Answer: {:.2f}

    The precision follows the dot, and f asks for fixed notation, so {:.2f} gives two digits after the decimal point. {:2} only sets a minimum width of 2 characters, and {:.2} without f sets two significant digits, which prints 3.1.

  8. Question 8 of 15 The scorecard prints each strike rate with {:>8.2f}. Ravi scored 9 off 14 balls. What does his row show at its end?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: 64.29, after 3 spaces

    100 × 9 ÷ 14 is 64.2857…, which .2f rounds to 64.29. The field is 8 characters wide and right-aligned, so the number's last digit lines up with 145.10 above it.

  9. Question 9 of 15 Which replacement field prints the word Scorecard centred in 35 characters, with dashes on both sides?

    Choose one answer.

    Show the answer: Question 9 of 15

    Answer: {:-^35}

    A format specification puts the fill character first, then the alignment (<, > or ^), then the width. The scorecard's line of dashes, {:-<35} with an empty value, uses the same order.

  10. Question 10 of 15 What does std::cin >> x do before it reads a number?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: It skips spaces, tabs and line breaks

    std::cin >> x skips any spaces, tabs and line breaks, then reads as many characters as fit the type of x. Several reads can be chained, and it makes no difference whether the values are on one line or several.

  11. Question 11 of 15 sum_runs.cpp is given 2 3 on one line and x 4 on the next. What does it print?

    Choose one answer.

    Show the answer: Question 11 of 15

    Answer: 5 runs off 2 balls

    The loop stops at the end of the input, and also at the first word that is not a number. Here that is x, after two good reads.

  12. Question 12 of 15 A program reads an age with std::cin >> age and then a name with std::getline(std::cin, name). Why is the name empty?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: The line break after the age is still in the input, and getline reads up to it

    >> stops at the line break after 19 and leaves it waiting. getline then reads until the first line break, which comes at once, and returns an empty line. std::getline(std::cin >> std::ws, name) skips it first.

  13. Question 13 of 15 What does std::getline(std::cin, line) read?

    Choose one answer.

    Show the answer: Question 13 of 15

    Answer: Everything up to the next line break, spaces included, and it removes the line break

    std::getline reads everything up to the next line break, spaces included, and removes the line break. Right after a >>, the next line break is usually the one >> left behind.

  14. Question 14 of 15 int overs = -1; and then std::cin >> overs meets the word twenty. What does overs hold afterwards?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: 0, and the stream is marked as failed

    Since C++11 a failed conversion stores zero, and the stream's fail state is set, so later reads fail at once until clear() is called. The lesson's program printed "overs is now 0".

  15. Question 15 of 15 read_overs.cpp is given 75. Which message does it print, and why?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: 75 is outside 1-50. Try again., because the read worked but the range test failed

    The program tests the read and the range together, then whether the input ended, then whether the read failed. For 75 the read worked, so it says the number is out of range, ignores the rest of the line and asks again.

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

  1. Question 1 of 2 An interviewer follows up: your program writes std::cout << answer << '\n'; and then reads the next query with std::cin >> next;. Does the answer reach the other side before your program waits?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Yes, because by default std::cin flushes std::cout before it reads

    A prompt written with std::cout always shows before the program waits, because std::cin flushes std::cout before every read. Flush yourself only when nothing reads in between, for example before a long computation.

  2. Question 2 of 2 And then: a program writes 200,000 lines to a file with std::endl, and it is slow. What do you change?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Write '\n' in the loop, and leave the flushing to the stream and to the end of the program

    Use '\n' by default and flush deliberately only when the text must appear at once. Writing a million lines took 1.1 to 5.9 seconds with std::endl against 20 to 190 ms with '\n' in the lesson's runs.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • std::cin, std::cout and std::cerr (from <iostream>) read standard input and write standard output and standard error; C++23’s std::print and std::println (from <print>) format output in one call.
  • Inside {}, :.2f sets the decimals, :<8, :>8 and :^8 the alignment and width, and :#x and :b the base.
  • Use '\n', not std::endl, to end lines: flushing every line was 25 to 65 times slower when writing a file.
  • std::cin >> x skips 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 with std::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 check eof() 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.