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++
#include <format>
#include <iostream>
using namespace std;
int main()
{
int num = 42;
std::string name = "John" ;
std::string formatted_str = std::format(
"My name is {} and my favorite number is {}" , name,
num);
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++
#include <format>
#include <iostream>
int main()
{
int num = 42;
std::string name = "John" ;
std::string formatted_str = std::format(
"My name is {1} and my favorite number is {0}" , num, name);
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++
#include <format>
#include <iostream>
int main()
{
double num = 3.14159;
std::string name = "John" ;
std::string formatted_str = std::format(
"My name is {1:.2s} and pi is {0:.2f}" , num, name);
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
C++ 20 - Ranges Library
C++20 introduces the header, which presents a fresh method of handling ranges comprising arrays, vectors, or alternative data structures. With this header, you can take advantage of a set of standard algorithms that support activities like data filtering, transformation, and sorting. This approach e
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
C++ sizeof Operator
The sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespac
3 min read
C++ Programming and STL Facts
C++ is widely used for competitive programming. It is preferred because of its reliability, efficient execution, short snippets, etc. It has become adaptive by most coders as it also provides the benefits of Standard Template Library(STL). C++ STL is the backbone of programming. The inbuilt function
5 min read
std::minus in C++
Binary function object class whose call returns the result of subtracting its second argument from its first argument (as returned by the binary operator -). Syntax : template struct minus : binary_function { T operator() (const T& x, const T& y) const {return x-y;} }; Template parameters :
2 min read
STD::array in C++
The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
5 min read
C++ 20 - <numbers> Header
C++20 has a recently developed header file labeled that incorporates mathematical functions and constants. Its purpose is to provide standard library support for mathematical operations, simplifying the process for C++ programmers to incorporate mathematical functions and constants into their progra
3 min read
C++ Cheatsheet
This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can
15+ min read