Preview: C++23 Print

C++23 introduced std::print() and std::println() as an easier way to output formatting strings to the console.

Here’s a Hello, World:

Listing 67 print_hello.cpp
#include <print>

int main() {

    std::println("Hello, World!");

}

The only difference between print() and println() is that the latter adds a newline.

Tip

Just like with our mdspan example, we need to use a compiler and library that support C++23. We can compile, for example, as:

clang++ -std=c++23 -stdlib=libc++  -o print_example print_example.cpp

Formatting

The strings that are passed into print() or println() are actually std::format_string and can specify where to insert variables and their formatting:

Listing 68 formatting_example.cpp
#include <print>
#include <string>

int main() {

    double x{1.0};
    int i{2};
    std::string a{"example"};

    std::println("x = {}, i = {}, a = {}", x, i, a);

    std::println("x = {:5.2f}, i = {:03d}, a = {:^20}", x, i, a);

}

The format codes are described here: https://en.cppreference.com/w/cpp/utility/format/spec