Mastering C++ std::format: Examples & Usage Guide
C++'s std::format function, introduced in C++20, provides a powerful and intuitive way to perform string formatting. It simplifies string concatenation and improves code readability by enabling type-safe and expressive formatting. Here, we'll explore std::format examples, demonstrating its usage and benefits.
Suppose we have a simple task of printing a person's full name, given their first and last names. Here's how you can achieve this using std::format:
Basic Formatting
Before C++20, string formatting required using std::string concatenation or C-style interpolation.
With std::format, you can replace this with a clear and expressive statement:
String Interpolation
Here's how you can print a full name using std::format:
The output will be: Full name: JohnDoe
As you can see, std::format simplifies the code by using brace-enclosed placeholders for arguments, improving readability.
Named Arguments
You can also use named arguments in std::format, which can make your code even more self-explanatory:
```cpp std::cout << std::format("Full name: {first}{last}", first = first_name, last = last_name); ```The output remains the same, but now, the purpose of each argument is clear, even without reading the entire code.
Formatting Options
Sometimes, you need control over the appearance of formatted strings. std::format supports various formatting options through format specifiers, similar to std::printf.
Let's print a person's age with proper formatting:
Width and Fill
You can specify the minimum field width and a fill character. If the field width is larger than the value, the value is padded with the fill character:
```cpp int age = 25; std::cout << std::format("Age: {:*>5}", age); ```The output will be: Age: *25
Here, '*' represents the fill character, and '>' indicates right alignment.
Precision
For floating-point numbers, you can control the number of decimal places:
```cpp double pi = 3.14159; std::cout << std::format("Pi: {:.2f}", pi); ```The output will be: Pi: 3.14
In the above example, '.2' specifies the precision (number of decimal places).
std::format provides numerous other formatting options, allowing you to control alignment, base (for integers), and more. Additionally, it's type-safe, meaning you can't insert an integer where a string is expected without a cast.
Compound Formatting
You can nest format specifiers to create complex formatting expressions. Here's an example of printing a student's score, with a custom grade based on the score:
Conditional Formatting
You can use conditional statements inside format specifiers using the ternary operator. Here's how you can achieve this:
```cpp int score = 85; std::cout << std::format("Score: {}. Grade: {}", score, score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : score > 60 ? "D" : "F"); ```The output will be: Score: 85. Grade: B
As you can see, std::format enables concise, readable, and type-safe string formatting in C++.
**Try std::format in your next project and enjoy the improved code readability and expressiveness!**