Format Text with C++20’s Format Library

Learn to format text with C++20’s format library.

C++20 introduces the new format() function, which returns a formatted representation of its arguments in a string. format() uses a Python-style formatting string, with concise syntax, type safety, and excellent performance.

The format() function takes a format string and a template, parameter pack, for its arguments:

template< class... Args >
string format(const string_view fmt, Args&&... args );

The format string uses curly braces {} as a placeholder for the formatted arguments:

const int a{47};
format("a is {}\n", a);

Output:

a is 47

It also uses the braces for format specifiers, for example:

format("Hex: {:x} Octal: {:o} Decimal {:d} \n", a, a, a);

Output:

Hex: 2f Octal: 57 Decimal 47

This recipe will show us how to use the format() function for some common string formatting solutions.

Note: This course was developed using a preview release of the Microsoft Visual C++ compiler on Windows 10. At the time of writing, this is the only compiler that fully supports the C++20 <format> library. Final implementations may differ in some details.

How to do it

Let's consider some common formatting solutions using the format() function:

  • We'll start with some variables to format:

const int inta{ 47 };
const char * human{ "earthlings" };
const string_view alien{ "vulcans" };
const double df_pi{ pi };

The pi constant is in the <numbers> header and the std::numbers namespace.

  • We can display the variables using ...

Get hands-on with 1400+ tech skills courses.