Open In App

C++ 20 - std::format

Last Updated : 15 May, 2023
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

C++20 comes with a host of new features and improvements, including the format() function. In this article, we will explore how std::format can be used to format strings in C++20.

C++20 - std::format

std::format is a new function Introduced in C++20 that provides a way to format strings by replacing placeholders inside a format string with the values of the provided arguments. The placeholders are represented using "{}" inside the format string.

Syntax:

std::string std::format(std::string_view format_string, Args... args);

Return type: The function returns a std::string that contains the formatted output.

In C++20, a new data type named "std::string_view" is introduced, which provides a view of the underlying string. It works similarly to a pointer to a string but with additional safety and convenience features. The "Args..." represents a variadic parameter, which means that the std::format function can take a variable number of arguments of any type.

Examples of C++ 20 - std::format

Example 1:

The following code demonstrates how to use std::format to format a string with placeholders for variables.


Output

My name is John and my favorite number is 42

In the above example, we have a format string that contains two placeholders, "{}". We pass the values of the variables "name" and "num" to the std::format function, which replaces the placeholders with the values of the variables. The resulting string is stored in the variable "formatted_str", which is then printed to the console.

Example 2:

In the following example, we will understand the positional arguments with std::format. 


Output

My name is John and my favorite number is 42

In the above example, we have reversed the order of the arguments in the std::format function, and we have added positional indices to the placeholders. The first placeholder is replaced with the value of "num" and the second placeholder is replaced with the value of "name".

Example 3:

In the following example, we will see how std::format provides many options for formatting strings, where we can use the "{}" placeholders to specify formatting options for each argument. 


Output

My name is Jo and pi is 3.14

In the above example, we have added formatting options to the placeholders. The first placeholder is formatted as a floating-point number with two decimal places, and the second placeholder is formatted as a string with a maximum width of two characters.

Conclusion

std::format supports a wide range of formatting options, including the ability to format user-defined types. It is more efficient than previous string formatting options in C++, such as sprintf and printf.


Article Tags :
Practice Tags :

Similar Reads