Open In App

C++ 20 – std::format

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
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.

C++




// C++ Program to implement
// C++ 20 - std::format
#include <format>
#include <iostream>
  
using namespace std;
  
int main()
{
    // Declare variables
    int num = 42;
    std::string name = "John";
  
    // Use std::format to format a string with placeholders
    // for variables
    std::string formatted_str = std::format(
        "My name is {} and my favorite number is {}", name,
        num);
  
    // Print formatted string to console
    std::cout << formatted_str << std::endl;
  
    return 0;
}


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. 

C++




// C++ Program to implement
// C++ 20 - std::format
#include <format>
#include <iostream>
  
int main()
{
    // Declare an integer variable named num
    // and initialize it with the value 42
    int num = 42;
    // Declare a string variable named name
    // and initialize it with the value "John"
    std::string name = "John";
  
    // Call the std::format function to create a formatted
    // string with placeholders for num and name The first
    // placeholder is represented by {0} and is replaced by
    // the value of num The second placeholder is
    // represented by {1} and is replaced by the value of
    // name
    std::string formatted_str = std::format(
        "My name is {1} and my favorite number is {0}", num, name);
  
    // Print the formatted string to the console
    std::cout << formatted_str << std::endl;
    return 0;
}


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. 

C++




// C++ Program to implement
// C++ 20 - std::format
#include <format>
#include <iostream>
  
int main()
{
  
    // Declare and initialize a double variable.
    double num = 3.14159;
  
    // Declare and initialize a string variable.
    std::string name = "John";
  
    // Format a string with two placeholders, one for a
    // double and another for a string. The first
    // placeholder formats the double with two decimal
    // places and the second placeholder truncates the
    // string to two characters.
    std::string formatted_str = std::format(
        "My name is {1:.2s} and pi is {0:.2f}", num, name);
  
    // Print the formatted string to the console.
    std::cout << formatted_str << std::endl;
  
    return 0;
}


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads