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>
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 ofparaminformat.
The format() function returns a string that is the arguments param formatted as format.
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");}
Hello world!!
My name is Ali. I love Educative.
{} is used as the placeholder of the string “world.” At runtime, {} is replaced with the string “world.”{0} is replaced with the first string to be formatted, “Ali.” Similarly, {1} is replaced with the second string to be formatted, “Educative.”Free Resources