Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 171 ยท Getting Started

Printing Output

Print text and values in C++ with std::println, std::print and format strings, use std::cout with <<, prefer '\n' to std::endl, and write to std::cerr.

Almost every program needs to show results: a calculation, a report, a progress message or an error. C++ gives you two families of tools for this. The modern one is std::print and std::println (C++23), which use format strings with {} placeholders. The classic one is std::cout with the << operator, which has been around since the 1990s and appears in nearly every existing C++ codebase.

You'll learn both in this lesson. You'll also meet escape sequences for special characters, see why std::endl is usually the wrong choice, and learn to send error messages to their own stream with std::cerr.

std::println and std::print

Include <print>, then call std::println to print a line of text followed by a line break, or std::print to print without the line break:

C++ print vs println

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::print leaves the cursor at the end of the text, so the next output continues on the same line. std::println("") prints just a line break. C++26 adds std::println() with no arguments for the same job; GCC 15 already accepts it, but older compilers need the empty string.

Placeholders

The first argument is a format string. Each {} in it is a replacement field, and the remaining arguments fill those fields in order. Arguments can be any mix of text, numbers, characters and booleans:

C++ Filling placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few details worth noticing in the output:

  • bool values print as true and false.
  • Floating-point numbers print in the shortest form that represents the exact value. That's why 0.1 + 0.2 shows 0.30000000000000004: this is the true stored value, not a printing bug. You'll learn why in Floating-Point Numbers.
  • and choose arguments by position (counting from 0). You can't mix numbered and empty {} fields in one format string.
  • To print a literal brace, double it: {{ prints { and }} prints }.

Format specifications

Inside the braces, after a colon, you can add a format specification that controls how the value looks. Here are the ones you'll use most:

C++ Width, alignment and precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output is:

TEXT
[3.14]
[   3.142]
[   right]
[left    ]
[  mid   ]
[00042]
[ff] [101]

That's enough to make tidy tables already. The full mini-language (fill characters, signs, +, hex prefixes, formatting containers) is covered in Formatting with std::format and std::print.

Mistakes are caught at compile time

The format string is checked while compiling. If the placeholders and arguments don't match, the program doesn't build. Run this; it fails on purpose:

C++ Too few arguments (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first error line says call to consteval function 'std::basic_format_string<...>("{} scored {} points")' is not a constant expression, which is GCC's way of saying the format string is invalid for these arguments. The long notes after it mention __invalid_arg_id_in_format_string, which is the real reason: the second {} has no argument. Add a second argument and it compiles. This compile-time checking is a big advantage over C's printf, which happily prints garbage or crashes when the arguments don't match.

std::cout and the << operator

The classic way to print is std::cout from <iostream>. You send values to it with <<, the insertion operator, and you can chain as many as you like:

C++ Printing with std::cout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Compare the output with the println version above and you'll spot the differences:

  • std::cout never adds a line break; you write '\n' (or "\n" inside a string) yourself.
  • bool prints as 1 and 0 unless you add std::boolalpha to the stream.
  • double values print with 6 significant digits by default, so 0.1 + 0.2 shows as 0.3. Large values switch to scientific notation: 123456789.0 prints as 1.23457e+08. Control this with manipulators like std::fixed and std::setprecision, covered in I/O Streams in Depth.
  • Spaces between values are your job: std::cout << 1 << 2 prints 12.

Which one should you use?

std::println / std::print std::cout <<
Header <print> (C++23) <iostream> (all versions)
Line break println adds one You add '\n'
Formatting Format specs inside {} Manipulators (std::setw, std::fixed, ...)
Errors in format Caught at compile time No format string to get wrong
Speed Generally faster Slower by default
Where you'll see it New code Almost all existing code

This course uses std::println in most examples because it's clearer and harder to get wrong. Use std::cout when your compiler is older than C++23 support, when the codebase already uses streams, or when you print your own types through an overloaded << (you'll learn that in Operator Overloading).

std::endl vs '\n'

You'll see std::endl in many tutorials and older code:

C++
std::cout << "Hello" << std::endl;

std::endl does two things: it writes a line break and flushes the stream. Flushing forces any buffered output to be handed to the operating system immediately. Output is normally collected in a buffer and written in large chunks because that's much faster than writing one line at a time. Flushing after every line throws that advantage away; in a loop printing many lines, std::endl can make a program several times slower.

So the rule is simple: use '\n' for line breaks, and flush explicitly with std::flush (or std::cout.flush()) only when you need output to appear right now, for example before a long computation. std::cerr, which you'll meet below, is never buffered, so error messages always appear immediately.

Escape sequences

Some characters can't be typed directly inside a string literal, such as a line break or a double quote (which would end the string). You write them as escape sequences, starting with a backslash:

Sequence Meaning
\n New line
\t Tab
\\ A backslash
\" A double quote
\' A single quote (needed in character literals: '\'')
\0 The null character (value 0)
\x41 The character with hex code 41 (A)
\u00E9 A Unicode character by code point (รฉ)

For text with lots of backslashes or quotes, like Windows paths or regular expressions, a raw string literal is easier. Everything between R"( and )" is taken literally, including line breaks:

C++ Escape sequences and raw strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Note: Tabs move to the next tab stop (usually every 8 columns), so they don't line up reliably when values have different lengths. For aligned columns, use format widths like {:<10} instead.

Errors go to std::cerr

Programs have two separate output streams: standard output (stdout) for normal results and standard error (stderr) for error and diagnostic messages. Keeping them apart lets users redirect the results to a file (program > results.txt) while still seeing errors in the terminal.

In C++ you write to standard error with std::cerr, or by passing stderr as the first argument to std::println:

C++ Normal output and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Our editor shows stdout and stderr separately, so the two error lines appear in their own section. (stderr itself is declared in <cstdio>.) There's also std::clog, a buffered version of std::cerr meant for logging. A common convention is to start messages with error: or warning: so they're easy to spot and search for.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::println("{} has {} items", "Cart", 3); print?

    Each {} is replaced by the next argument in order, and println adds a line break at the end.
  2. 2. What does std::cout << 2 << 3 << "\n"; print?

    << just writes each value in turn. It doesn't add anything between them, so you get 23.
  3. 3. Why is '\n' usually preferred over std::endl?

    Both write a line break, but std::endl also forces a flush. Unneeded flushes make output much slower.
  4. 4. What does std::println("{:.1f}", 2.46); print?

    .1f means fixed notation with one digit after the decimal point, and the value is rounded, giving 2.5.
  5. 5. Which line prints exactly Say "hi"?

    Inside a string literal, a double quote must be escaped as \". Without the backslash, the quote ends the string early.

Summary

  • std::println (from <print>) prints a line; std::print prints without a line break.
  • Format strings use {} placeholders filled in order; picks by position, {{ and }} print braces.
  • Format specs like {:.2f}, {:>8} and {:05} control precision, alignment and padding; mismatched placeholders are compile-time errors.
  • std::cout << a << b is the classic stream style: no automatic line breaks, bool as 1/0, and 6 significant digits for doubles.
  • Use '\n' for line breaks; std::endl also flushes and is slower.
  • Escape sequences (\n, \t, \\, \") write special characters; raw strings R"(...)" avoid escaping.
  • Send errors to standard error with std::cerr or std::println(stderr, ...).

Next: Reading User Input, where your programs start asking questions with std::cin and std::getline.