Format Strings
Explore what C++20 holds for formatting strings.
We'll cover the following...
The formatting string syntax is identical for the formatting functions std::format
, std::format_to
, and std::format_to_n
. I use std::format
in my examples.
- Syntax:
std::format(FormatString, Args)
The format string FormatString
consists of
- Ordinary characters (except
{
and}
) - Escape sequences
{{
and}}
that are replaced by{
and}
- Replacement fields
A replacement field has the format { }
- You can use inside the replacement field an argument id and a colon followed by a format specification, both components are optional.
The argument id allows you to specify the index of the arguments in Args
. The ids start with 0. When you don’t provide the argument id, the fields are filled in the same order as the arguments are given. Either all replacement fields have to use an argument id or none; i.e., std::format("{}, {}", "Hello", "World")
and std::format("{1}, {0}", "World", "Hello")
will both compile, but std::format("{1}, {}", "World", "Hello")
won’t.
std::formatter
and its specializations define the format specification for the argument types.