Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Strings and I/O

C++ std::format function

Reference for std::format: replacement fields, positional arguments, format_to, format_to_n, formatted_size, vformat, compile-time checks and format_error.

std::format (C++20, header <format>) builds a std::string from a format string and a list of arguments. Each {} in the format string is a replacement field that is filled with the next argument, formatted according to its type and an optional specification after a colon, such as {:>8.2f}.

It combines the readability of printf with type safety: the argument types are known, so there is no %d versus %ld mismatch, and the format string is checked at compile time. Unlike stream manipulators, the formatting options live in the string and do not leak into later output.

C++
#include <format>
#include <string>

std::string s = std::format("{} scored {:.1f}%", "Ada", 97.456);
// "Ada scored 97.5%"

Try it

C++ Fields, positions and widths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ format_to, format_to_n and formatted_size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class... Args>
std::string format(std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
Out format_to(Out out, std::format_string<Args...> fmt, Args&&... args);

template<class Out, class... Args>
std::format_to_n_result<Out> format_to_n(Out out, std::iter_difference_t<Out> n,
                                         std::format_string<Args...> fmt, Args&&... args);

template<class... Args>
std::size_t formatted_size(std::format_string<Args...> fmt, Args&&... args);

std::string vformat(std::string_view fmt, std::format_args args);
Name Description
fmt The format string. Literal text, {{ and }} for braces, and replacement fields {index:spec}.
args The values to format.
out An output iterator that receives the characters (for example std::back_inserter(str)).
n The maximum number of characters format_to_n may write.

Returns: format returns the formatted std::string. format_to returns the iterator past the last character written. format_to_n returns a struct with out (the end iterator) and size (the characters the full result would have). formatted_size returns the length of the full result.

Errors / undefined behavior: with a string literal as the format, a bad format string or an argument mismatch is a compile-time error. With vformat (or an invalid runtime string) the same problems throw std::format_error. Mixing automatic ({}) and manual () numbering in one string is an error.

Usage notes

  • Compile-time checking. The first parameter is std::format_string, constructed from a constant expression, so std::format("{:d}", "text") does not compile. To format with a string that is only known at run time, use std::vformat with std::make_format_args. It takes lvalues, so store temporaries in variables first.
  • Locale independent by default. {} always uses the "C" style (for example 1234.5). Add L to the specification ({:L}) to use the locale's separators and decimal mark.
  • Wide characters work with std::wformat_string and a std::wstring result.
  • Performance. format_to into a back_inserter or a buffer avoids the intermediate string that format returns. formatted_size lets you reserve exactly.
  • User types are formattable when they specialize std::formatter. See custom formatters. Ranges (vectors, sets, maps) and tuples are formattable out of the box in C++23: std::format("{}", std::vector{1, 2}) gives [1, 2].
  • Output with std::cout << std::format(...) works everywhere. From C++23, std::print does the formatting and the output in one call.
  • Standard library support. <format> ships with GCC 13 and later, Clang 17 and later and MSVC 2019 16.10 and later.