Format Strings

Explore what C++20 holds for formatting strings.

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.

I will use the next sections to fill in the theory with practice. Let me start with the argument id and continue with the format specification.

Argument ID

Thanks to the argument id, you can reorder the arguments or address particular arguments.

Get hands-on with 1200+ tech skills courses.