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 you how to use the format()
function for some common string formatting solutions.
Note
This chapter was developed using a preview release of the Microsoft Visual...