skip to content

What do C++23 std::print and std::println add over writing a std::format result to std::cout?

level: middleimportance: should knowfreq 45%

answer

  1. format and write in one call
  2. C stream, not a C++ stream
  3. newline without a flush
  4. Unicode console output

basics

~20 s

std::print formats and writes in one call to a C stream, stdout by default, and std::println adds a newline without flushing. Each call writes its whole output as one operation, and Unicode text reaches consoles that need a native Unicode API intact.

solid answer

~50 s

`std::print` and `std::println` (C++23, header `<print>`) take the same checked `std::format_string` as `std::format` but write the result instead of returning it. With no stream argument they write to `stdout`, the C `FILE*`; overloads take another `FILE*` such as `stderr`, and `<ostream>` adds overloads taking a `std::ostream&`. `println` appends `'\n'` and does not flush, unlike `std::endl`. Each call formats the whole text and writes it as one operation on the stream (the C++26 wording, adopted as a fix, says it locks the stream), so lines from different threads do not interleave mid-line the way chained `<<` calls can. When the literal encoding is UTF-8 and the stream is a console that can only show Unicode through a native API, as on Windows, `print` writes through that API instead of the raw bytes. A formatting error or a failed write is reported by an exception, not a return code.

code

cpp · 17 lines
cpp
#include <cstdio>
#include <print>
#include <string>
#include <vector>

int main() {
    std::string server = "eu-west-3";
    int players = 118;
    double tick_ms = 15.6249;

    std::print("{}: ", server);
    std::println("{:>4} players, tick {:.2f} ms", players, tick_ms);
    std::println(stderr, "warning: tick {} ms is over budget", tick_ms);

    std::vector<int> lobbies{3, 7, 12};
    std::println("lobbies {}", lobbies);   // C++23 range formatting
}

go deeper

for a junior

Recall that std::print and std::println are C++23, take a {} format string, and that println adds a newline.

for a middle

Explain the target: stdout as a C FILE* by default, FILE* and std::ostream overloads, and a newline that does not flush.

for a senior

Show the production details: one write per call so threads do not split a line, Unicode output on native consoles, exceptions, and ordering with unsynchronised cout.

for a principal

Judge whether a C++23 toolchain floor is worth std::print over cout with std::format, given supported compilers and existing stream-based code.

## What the two functions are **C++23** added the header `<print>` with two function templates: - `std::print(fmt, args...)` formats the arguments exactly as `std::format` would, then writes the text. - `std::println(fmt, args...)` does the same and appends a newline. Their first parameter is the same `std::format_string<Args...>` that `std::format` takes, so the format string is checked against the argument types at compile time: ```cpp std::println("{}: {:>4} players, tick {:.2f} ms", server, players, tick_ms); ``` ## Where the text goes The standard defines the stream-less overloads as writing to `stdout`, the **C stream** (`FILE*`) from `<cstdio>`, not to `std::cout`: 1. `std::print(fmt, args...)` is equivalent to `std::print(stdout, fmt, args...)`. 2. `std::print(stderr, fmt, args...)` and the matching `println` write to any C stream you pass. 3. `<ostream>` declares overloads taking a `std::ostream&`, so `std::println(std::cout, ...)` or `std::println(logfile, ...)` work with C++ streams too. 4. `std::println()` with no arguments prints a blank line. It came as a later fix and is in the C++26 draft; libc++ 19 and later provide it in C++23 mode. Because the default target is `stdout`, ordering with `std::cout` output stays correct only while the C++ standard streams are synchronised with C stdio, which is the default. A program that called `std::ios::sync_with_stdio(false)` and then mixes `std::cout` and `std::print` can see lines appear out of order. ## Newline without a flush `std::println` appends `'\n'`. It does **not** flush, which is the difference from `std::cout << std::endl`. Whether a line becomes visible at once depends on the C stream's buffering: `stdout` is typically line-buffered when it is a terminal and fully buffered when it is a pipe or a file. When `stdout` is piped, a `println` to `stdout` can therefore appear after a later `println` to `stderr`. ## Locking and Unicode When the ordinary literal encoding is UTF-8, `print` goes through `vprint_unicode`. In the C++23 wording that function first formats the whole output into a string and then writes it to the stream. A later fix, adopted against C++23 and part of the C++26 draft, says outright that it **locks the stream**, writes, and unlocks it on exit; libc++'s status page still lists that fix as in progress. Either way, one call produces one write of the complete text. With `std::cout << a << b << '\n'`, each `<<` is a separate call, so output from two threads can interleave inside one logical line. The same function handles a problem `std::cout` never solved. When the stream is a console that needs a **native Unicode API** to display Unicode, `print` flushes the stream and writes through that API. The standard's note names `WriteConsoleW` on Windows. Everywhere else, the bytes are written unchanged. ## Compared with the alternatives | | `std::cout << std::format(...)` | `printf` | `std::print` | |---|---|---|---| | Format string checked at compile time | yes | no | yes | | Writes to | a C++ stream | a C stream | a C stream, or a C++ stream via `<ostream>` | | One write per logical line | no, one per `<<` | yes, per call | yes, per call | | Unicode on a native console | bytes only | bytes only | native Unicode API | | Error reporting | stream state flags | return value | exceptions | ## Errors and availability - A write failure throws `std::system_error`, a bad runtime format string throws `std::format_error`, and allocation can throw `std::bad_alloc`. Code that relied on checking `printf`'s return value must catch instead. - `std::print` needs **C++23** and a library that ships `<print>`: libstdc++ from GCC 14.1, libc++ from LLVM 18. Compiled with `-std=c++20`, `std::print` does not exist. - C++23 also made ranges formattable, so `std::println("{}", lobbies)` prints a `std::vector<int>` as `[3, 7, 12]`. ## When to reach for which 1. On a **C++20** toolchain, `std::cout << std::format(...)` or `std::fputs(std::format(...).c_str(), stdout)` gives checked formatting, with the C++ stream or the C stream as the sink. 2. On a **C++23** toolchain, `std::println` is the shortest correct way to write one checked line to standard output, and `std::println(stderr, ...)` the shortest way to report an error. 3. When output must reach a `std::ostream` that is not a standard stream, such as a `std::ofstream` log file or a `std::ostringstream` in a test, use the `std::ostream&` overloads from `<ostream>`, which keep the same format string checks. 4. When a line must appear before something slow happens, such as a progress line before a long computation, add an explicit `std::fflush(stdout)`; neither `print` nor `println` promises a flush.

  • Is std::println the same as writing std::endl?
    No. `std::endl` writes a newline and then flushes the stream. `std::println` writes a newline and leaves buffering to the C stream, which typically line-buffers a terminal and fully buffers a pipe or file. Call `std::fflush(stdout)` when you need the flush.
  • Why can std::print and std::cout output appear out of order?
    `std::print` with no stream writes to the C `stdout`. `std::cout` keeps its output in step with `stdout` only while the standard streams are synchronised with stdio. After `std::ios::sync_with_stdio(false)`, `std::cout` buffers on its own, and the two can reach the terminal in a different order.

  • std::println flushes the stream just like std::endl
  • std::print writes through std::cout under the hood
  • std::print is available in C++20 alongside std::format
  • std::print reports a failed write by returning a negative count
  • std::print skips the compile-time format string check that std::format does

Assumes C++23 for std::print and std::println; std::println() with no arguments came later as a fix in the C++26 draft.