How to format a string in C++20

We can use the format() function in C++20 to format strings. To use the format() function, we must include the following library:

#include <format>

Declaration

The format() function can be declared as follows:

template< class... T >
std::string format( const std::locale& local, format, const T &... param );

OR

template< class... T >
std::wstring format( const std::locale& local, format, const T &... param );
  • param: The strings being formatted.
  • format: The format string to format param. This is a parameter of unspecified type.
  • local: This is an optional parameter used for locale-specific formatting.

Note: We use {} as a placeholder of param in format.

Return type

The format() function returns a string that is the arguments param formatted as format.

Code

Consider the code snippet below, which demonstrates the use of the format() function:

#include <iostream>
#include <format>
int main() {
std::cout << std::format("Hello {}!! \n", "world");
std::cout << std::format("My name is {0}. I love {1}. \n", "Ali", "Educative");
}

Output

Hello world!!
My name is Ali. I love Educative.

Explanation

  • line 5: {} is used as the placeholder of the string “world.” At runtime, {} is replaced with the string “world.”
  • line 6: {0} is replaced with the first string to be formatted, “Ali.” Similarly, {1} is replaced with the second string to be formatted, “Educative.”
Copyright ©2024 Educative, Inc. All rights reserved