C++20 Formatting Library: Part-6 Characters and Strings

Gajendra Gulgulia
4 min readMar 12, 2023

In the fourth part and fifth part of the tutorial series on C++20 formatting library, the major focus was on formatting numbers. This part of the series will discuss majorly on how characters and strings can be formatted using the new formatting library.

Formatting strings with the formatting library is practically quite straight forward. Basically all the format specifier rules discussed so with basic arithmetic types except forsign applies to strings as well.

Let’s look at them one by one

1. Default formatting

If no format specifier is used the string is formatted as it is. The formatted string is to the beginning of the formatted space compared to arithmetic types which are at the end of the formatted space.

std::string str{"Hello C++20!"};
std::cout << fmt::format("{}", str);output
______
Hello C++20!

2. Width

The width format specifier is applied as usual to the formatting library. There are two possibilites for the width format specifier

  1. The specified width is less than the length of string: This has no effect on the formatted output. The string is not truncated in this case!
  2. The specified width is more than the length of string: This adds white space to the string and the width of the formatted output increases by the difference of width and string length.

--

--