C++ std::format Examples: Formatting Strings with Ease
The C++ Standard Library's std::format is a powerful tool introduced in C++20 for creating formatted output. It simplifies string formatting by providing a more expressive and readable alternative to std::string concatenation and printf-style functions.
In this article, you'll learn how to use std::format with clear examples and practical use cases. We'll explore its features, demonstrate formatting techniques, and discuss best practices.
Understanding std::format
std::format is a function template that produces a formatted string by taking a format string and a variable number of arguments. It follows the registry of format specifiers from the C++ Standard Library.
Here's a simple example of std::format in action:
Positional Arguments
In the example above, arguments are passed in their respective positions. This approach is useful for simple, predictable outputs.
Here's an example demonstrating positional arguments with different types:
```cpp std::cout << std::format("{0} + {1} = {2}", a, b, a + b); // Outputs: 10 + 5 = 15 ```Named Arguments
Starting from C++23, std::format supports named arguments, making the code more readable and maintainable.
Here's how you can use named arguments:
```cpp std::cout << std::format("{a} + {b} = {result}", a, b, result=a+b); // Outputs: 10 + 5 = 15 ```Formatting Options
std::format allows you to control the formatting of individual arguments. You can adjust the width, precision, and alignment of values.
Let's explore these formatting options with examples:
Width and Precision
You can specify the minimum field width and precision using : and . respectively. Here's an example:
Alignment
Use > or to left- or right-align values within their field. Here's an example:
```cpp
std::cout << std::format("{:>10}", "Hello"); // Outputs: Hello
```
Fill Character
You can change the fill character using the # symbol. By default, it's a space character. Here's an example:
```cpp
std::cout << std::format("{:-^20}", "Centered"); // Outputs: ─── Centered ───
```
Error Handling
std::format has built-in error handling. If the format string cannot be parsed or the specified arguments do not match the format specifiers, it throws a std::format_error exception.
Here's an example demonstrating error handling:
```cpp
try {
std::cout << std::format("{}: {}", "Apple", "Banana", "Cherry"); // Throws std::format_error
} catch (const std::format_error& e) {
std::cerr << "Format error: " << e.what() << '\n';
}
```
std::format is a powerful tool for creating formatted output in C++. It enhances code readability and maintainability by providing a more expressive way to format strings. By understanding its features and best practices, you can improve your C++ development experience.
To learn more about std::format, refer to the official C++ Standards Library documentation: std::format