Skip to main content

Section 11.1 std::format

We have seen some very basic tricks for formatting text - how to use tab and newline characters. But those tools are clumsy for making columns of text and do not help us do anything more complex. std::format is a function from the <format> library that helps to do things like:
  • Print out text in well aligned columns.
  • Easily combine other data types with strings.
  • Print out decimal values to different precision.
As with std::cout or std::endl, you can either use the full formal name of std::format or you can add using namespace std; to your file and then use the shorter format. Format is interesting in that it takes a variable number of arguments:
format(FORMAT_STRING, ARG1, ARG2, ...);
FORMAT_STRING is a string that contains the format you want to use and must always be provided. Think of it as a β€œMad Lib” style template with blanks that need be filled in. The blanks are represented by {} within the string. The other arguments are the values you want to place in those blanks. There needs to be as many extra arguments as there are blanks in the FORMAT_STRING. Here is a simple example that uses formats two extra arguments.
Listing 11.1.1.
Notice the two {} in the first parameter. Those are the locations where the next two parameters, name and age are placed. Also notice that we do not have to use to_string on age, format automatically turns the int into a string.
If we want to insert another variable’s value into the string being generated, we need to add another {} placeholder to the format string and then pass an additional parameter:
Listing 11.1.2.

Note 11.1.1.

std::format is new as of the C++20 standard. You will need to tell your compiler that you want to use C++20 features to make use of it.
There are other tools that can be used to format text. For example, printf is a function that has been around for a long time and is available in C and C++. You can also send special messages to cout to tell it things like β€œdisplay numbers with 4 digits of accuracy”. These other tools are still widely used, especially in code that has been around for a while. In this book, we will focus on std::format because it has the best combination of safety and simplicity for modern C++ programming.

Checkpoint 11.1.1.

You have attempted of activities on this page.