Back to C++
2025-12-186 min read

Formatters (C++)

Learn Formatters (C++) step by step with clear examples and exercises.

Why This Matters

Understanding formatters in C++ is crucial for developers who aim to write cleaner, more efficient, and easier-to-maintain code. Formatters simplify the process of formatting output, managing memory, and performing other common operations by automating repetitive tasks. In this tutorial, we will focus on the std::format function, a modern and flexible tool for formatting strings in C++.

Formatters can help developers write more readable and maintainable code by reducing the amount of boilerplate code needed to format output. They also provide better control over formatting options, making it easier to create consistent and attractive output. Additionally, formatters can help reduce memory usage by avoiding the need for temporary strings during formatting operations.

Prerequisites

To follow this tutorial, you should have a basic understanding of the following topics:

  1. C++ syntax and programming concepts (variables, functions, loops, etc.)
  2. Standard library including std::cout for console output
  3. Basic knowledge of string manipulation in C++
  4. Familiarity with the C++20 standard
  5. Understanding of exceptions and exception handling in C++

Core Concept

The std::format function is a powerful tool for formatting strings in C++, introduced in C++20. It provides a more flexible and readable alternative to traditional methods like using std::cout with std::setw, std::left, std::right, and other manipulators.

The std::format function takes a format string and a set of arguments, which can be variables or literals, and returns a formatted string as a std::string_view. Here's an example demonstrating its usage:

#include <iostream>
#include <format>
#include <string_view>

int main() {
int x = 42;
double y = 3.14;

std::string_view formatted_str = std::format("x: {}, y: {}", x, y);
std::cout << formatted_str << '\n';
}

In this example, the std::format function formats a string using the provided format string and arguments (x and y). The resulting formatted string is then stored in the formatted_str variable and printed to the console.

Placeholders

The format string contains placeholders for the arguments, which are enclosed within curly braces {}. By default, placeholders are replaced with the corresponding argument's value. You can specify the type of a placeholder by appending a colon (:) followed by the type name. For example:

std::string_view formatted_str = std::format("x: {:d}, y: {:f}", x, y);

In this case, {:d} is used for an integer (decimal) format and {:f} for a floating-point number.

Formatting options

You can customize the formatting of each placeholder by using various options. For example, to specify the precision for floating-point numbers, you can use the .precision() modifier:

std::string_view formatted_str = std::format("x: {:d}, y: {:.3f}", x, y);

In this example, the floating-point number is formatted with three decimal places.

Formatting flags

You can also use formatting flags to adjust the behavior of placeholders. For instance, to left-justify an integer, you can use the < flag:

std::string_view formatted_str = std::format("x: <{:5d}, y: {:f}", x, y);

In this example, the integer is left-justified within a field of width 5.

For a complete list of available placeholders and their options, refer to the C++ Reference.

Variable arguments

The std::format function does not support a variable number of arguments in its basic form. To handle a variable number of arguments, use the std::vformat function instead. This function takes a format string, an argument pack, and a formatter object (e.g., std::locale) as parameters. For more information, refer to the C++ Reference.

Worked Example

Now that you have learned about the basics of std::format, let's dive into a worked example. In this example, we will create a simple program that reads user input and formats it using various options:

#include <iostream>
#include <format>
#include <string_view>
#include <vector>

int main() {
std::vector<double> numbers;

while (true) {
double number;
std::cout << "Enter a number (or 0 to quit):\n";
if (!(std::cin >> number)) {
break;
}
numbers.push_back(number);
}

for (const auto& number : numbers) {
std::string_view formatted_str = std::format("Number: {:.2f}", number);
std::cout << formatted_str << '\n';
}
}

In this example, the program reads a series of floating-point numbers from the user and formats each one with two decimal places using std::format. The resulting formatted strings are printed to the console.

Common Mistakes

  1. Forgetting to include necessary headers: Make sure you have included the required headers (`, , and ) for using std::format`.
  2. Incorrect usage of placeholders: Ensure that placeholders are enclosed within curly braces {} and use the correct syntax for specifying types and options.
  3. Not handling exceptions properly: When using input operations, don't forget to handle potential exceptions (e.g., std::invalid_argument) to ensure your program behaves correctly in case of user errors.
  4. Ignoring formatting flags: Remember to use formatting flags like `, and .precision()` to customize the behavior of placeholders as needed.
  5. Misunderstanding variable arguments: The std::format function does not support a variable number of arguments in its basic form. To handle a variable number of arguments, use the std::vformat function instead.
  6. Not checking for input errors: When reading user input, always check if the input is valid before using it to avoid potential issues.
  7. Not considering localization: When working with internationalized applications, remember that formatting options may need to be adjusted based on the user's locale. Use the std::format_to function instead of std::format when dealing with localized output.

Practice Questions

  1. Write a program that formats a date using the std::format function in the following format: "Month Day, Year". Use the %Y, %m, and %d format specifiers for year, month, and day, respectively.
  2. Create a program that reads a user's age and formats it as an integer followed by the corresponding ordinal suffix (e.g., "1st", "2nd", etc.) using the std::format function.
  3. Write a program that takes a floating-point number as input and formats it with two decimal places, left-justified within a field of width 10, using the std::format function.
  4. Modify the worked example to handle exceptions when reading user input and print an error message if the input is invalid.
  5. Write a program that takes a date (year, month, day) as input and formats it in the "Month Day, Year" format using the std::format function. The program should also check for valid dates (i.e., ensure that the day is within the range of days for the given month).
  6. Write a program that reads a list of names from the user and formats each name with an uppercase first letter and lowercase remaining letters using the std::format function.
  7. Create a program that takes a temperature (in Celsius) as input, converts it to Fahrenheit using the formula (9/5)*C + 32, and formats the result with two decimal places using the std::format function.

FAQ

Q: Can I use std::format for formatting output to the console?

A: Yes, you can use std::format for formatting strings that are printed to the console using std::cout. The resulting formatted string can be stored in a variable (e.g., std::string_view) and then printed.

Q: Can I use std::format with older versions of C++?

A: No, std::format is only available in C++20 and later versions. If you need to support older compilers, consider using alternative methods like std::printf or manual string manipulation.

Q: How can I format a string with a variable number of arguments?

A: You can use the std::vformat function for formatting strings with a variable number of arguments. This function takes a format string, an argument pack, and a formatter object (e.g., std::locale) as parameters. For more information, refer to the C++ Reference.

Q: How can I format numbers based on the user's locale?

A: To format numbers based on the user's locale, use the std::format_to function instead of std::format. This function takes a stream insertion operator (e.g., <<) and a formatter object (e.g., std::locale) as parameters. For more information, refer to the C++ Reference.

Formatters (C++) | C++ | XQA Learn