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.
Similar Reads
C++ 20 - std::span
C++20 introduced the std::span class template as part of the C++ Template Library which represents an object that provides a way to view a contiguous sequence of objects. This feature offers a flexible and efficient way to work with contiguous sequences of objects. It is defined inside <span>
3 min read
Features of C++ 20
C++ has a tradition of introducing new improvements and features in every 3 years in the form of a standard. With the last standard having released in 2017 as C++ 17, C++20 is going to be the latest standard. Below here are some major features in C++ 20: C++ Concepts library3-way comparisonsMap cont
8 min read
std::quoted in C++ 14
std::quoted is an I/O manipulator function that was introduced in C++ 14 as the part of <iomanip> library. Its primary purpose is to handle the quoted string in the input and output operations. In this article, we will learn about the std::quoted manipulator, how it works and how to use it in
5 min read
Output of C++ programs | Set 42
Prerequisite : Pointers and References Q.1 What Is The Output Of this program? CPP #include <iostream> using namespace std; void fun(int& a, int b) { a += 2; b += 1; } int main() { int x = 10, y = 2; fun(x, y); cout << x << " " << y << " "; fun(x
4 min read
Output of C programs | Set 52
1. What will be the output of following program? CPP #include <stdio.h> int main() { int a = 5, *b, c; b = &a; printf("%d", a * *b * a + *b); return (0); } Options: 1. 130 2. 103 3. 100 4. 310 The answer is the option(1). Explanation: Here the expression a**b*a + *b uses pointer
3 min read
Output of C++ programs | Set 22
Predict the output of the following C++ programs. Question 1 CPP #include <iostream> using namespace std; int main() { int a = b = c = 0; cout << a << "*" << b << "*" << c; return 0; } Output: Compile time error! Explanation: A chained statemen
4 min read
C++ 03 Standard
The C++ programming language, initially developed by Bjarne Stroustrup in 1983, quickly became one of the most popular programming languages due to its efficiency, flexibility, and support for object-oriented programming. However, as the language evolved, variations and extensions introduced by diff
4 min read
C++ 23 Standard
C++23, officially known as ISO/IEC 14882:2023, is the latest standardized version of the C++ programming language, published in 2023. As C++ introduces new improvements and features every 3 years in the form of a standard like C++20 introduced powerful features such as concepts, ranges, and coroutin
6 min read
Output of C++ Program | Set 19
Predict the output of following C++ programs. Question 1 C highllight=12-5 #include <iostream> #include <string.h> using namespace std; int main() { cout << sizeof("GeeksforGeeks") << endl; cout << strlen("GeeksforGeeks"); return 0; } Output: 14 13 S
3 min read
Output of C programs | Set 54
1. What will be the output of the below program? C++ #include <stdio.h> #define GEEKS 100 int main() { #define GEEKS 100 printf("%d", GEEKS); return (0); } Output: - 100 Options: 1. 100 2. compile error 3. No output 4. abnormal termination The answer is option(1). Explanation: As GEE
2 min read