Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 171 ยท Strings

Formatting with std::format and std::print

The complete guide to C++ std::format and std::println - width, fill, alignment, precision, signs, hex and binary, formatting vectors and maps, custom formatters, iomanip.

Almost every program turns values into text: a log line, a receipt, a table of results, a file name with a number in it. For decades C++ offered two unsatisfying ways to do this. C's printf is compact but not type-safe, so a wrong %d can crash your program. Streams (std::cout << ...) are type-safe but verbose, and their formatting flags stick around and leak into later output.

C++20 added std::format (header <format>), and C++23 added std::print and std::println (header <print>). They combine the best of both: short {} placeholders like Python's f-strings, full type safety, and format strings that are checked at compile time. This lesson covers the whole format-spec language (width, fill, alignment, signs, precision, number bases), formatting containers (C++23), writing a formatter for your own types, and the <iomanip> equivalents you'll still meet in stream code.

The basics: format, print and println

All three functions take a format string followed by the values to insert. Each {} is a replacement field:

  • std::format(fmt, args...) returns a std::string.
  • std::print(fmt, args...) writes to standard output (or to a FILE* or stream you pass first).
  • std::println(fmt, args...) does the same and adds a newline.
C++ Replacement fields

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.

You can number all fields (, ) or none of them, but not mix the two styles in one format string. Doubled braces {{ and }} print a single literal brace.

Format strings are checked at compile time

The format string must normally be a compile-time constant. The compiler parses it and checks that the number of fields and every format spec fit the arguments. A mistake is a compile error, not a crash at 3 a.m.:

C++
std::println("{} and {}", 42);      // error: not enough arguments
std::println("{:d}", "text");       // error: 'd' is not valid for strings
std::string fmt = "{}";
std::println(fmt, 42);              // error: fmt is not a constant expression

When the format string really is only known at runtime (for example, loaded from a translation file), use std::vformat(fmt, std::make_format_args(args...)). Errors are then reported at runtime by throwing std::format_error. C++26 adds std::runtime_format(fmt) as a friendlier spelling.

The format spec mini-language

Inside the braces, after an optional argument number, a colon introduces the format spec. Every part is optional, but the parts must appear in this order:

TEXT
{ arg-id : fill-and-align  sign  #  0  width  .precision  L  type }
Part Examples Meaning
fill and align <, >, ^, *^ left, right, center; an optional fill character before it
sign +, -, space show + on positives, only - (default), or a space for positives
# {:#x} alternate form: 0x, 0b, 0 prefixes; always show a decimal point
0 {:08} pad numbers with leading zeros (after the sign and prefix)
width {:10}, {:{}} minimum field width; {} takes it from an argument
precision {:.2f}, {:.3} digits for floats, maximum characters for strings
L {:L} use the locale (digit grouping, decimal separator)
type d x X o b B c e f g a s ? presentation, depends on the argument's type

Width, fill and alignment

Width sets the minimum number of characters; longer values are never cut. By default numbers align right and text aligns left. Put <, > or ^ before the width to choose, and put any character (except { and }) before the alignment to fill with it.

C++ A receipt with aligned columns

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.

{:-<36} with an empty string is a neat way to draw a line: fill character -, left-aligned, width 36. The last line shows dynamic width: a nested {} inside the spec takes the width from the next argument (with positional fields you write {0:>{1}}). Precision can be dynamic the same way: {:.{}f}.

Integers: signs, bases and zero padding

For integers the type letter picks the base: d decimal (the default), x/X hexadecimal, o octal, b/B binary, and c for the character with that code. # adds the matching prefix, and 0 pads with zeros after the sign and prefix, which is exactly what you want for things like 0x00ff.

C++ Integer formatting

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.

Note that {:05} on -42 gives -0042: the sign counts toward the width and the zeros go after it.

Floating-point: precision and presentation

With no spec, a double prints in the shortest form that reads back as exactly the same value. That's why 0.1 + 0.2 shows its true value 0.30000000000000004 instead of hiding it. When you want a fixed look, choose a presentation type:

Type Meaning Example with 1234.5678
f fixed decimal places {:.3f} โ†’ 1234.568
e / E scientific {:.3e} โ†’ 1.235e+03
g / G general: fixed or scientific, precision = significant digits {:.3g} โ†’ 1.23e+03
a / A hexadecimal floating point {:a} โ†’ 1.34a456d5cfaadp+10
% not supported: multiply by 100 yourself
C++ Floating-point formatting

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.

Rounding uses the exact binary value, so {:.2f} of 2.675 gives 2.67: the stored double is slightly below 2.675. If you need exact decimal rounding for money, store cents in an integer instead (see Floating-Point Numbers).

Strings, characters, booleans and pointers

  • Strings (std::string, std::string_view, const char*) accept width, fill, alignment and precision, which truncates: {:.3} of "truncate" prints tru.
  • ? (C++23) prints the "debug" form: strings in quotes with escapes, characters in single quotes. {:?} of a string containing a tab prints "a\tb". Great for logging user input.
  • bool prints true/false; {:d} prints 1/0.
  • Pointers: only void*, const void* and nullptr are formattable. Cast other pointers with static_cast<const void*>(p). They print in hex like 0x7ffd5c3a1b2c ({:p} is the explicit type).
C++
std::println("[{:>8}] [{:.3}] {:?} {:?}", "right", "truncate", "tab\there", 'x');
// [   right] [tru] "tab\there" 'x'
std::println("{} {:d}", true, true);              // true 1
int value = 5;
std::println("{}", static_cast<const void*>(&value));   // an address like 0x7ffc...

Formatting containers and ranges (C++23)

C++23 makes containers, ranges, std::pair and std::tuple formattable out of the box. Sequences print in square brackets, sets in braces, maps as {key: value} pairs, and pairs/tuples in parentheses. Strings and characters inside containers use the debug form, so you can see exactly where each element starts and ends.

After the first colon you can add range options: n removes the brackets. A second colon applies a spec to every element.

C++ Printing vectors, maps and tuples

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.

Before C++23 you had to write a loop for every container you wanted to print. Range formatting needs GCC 15, Clang 17+ with libc++, or a recent MSVC. On older compilers, the open-source {fmt} library that std::format grew out of offers the same syntax.

Formatting your own types

To make your own type work with std::format and std::println, specialize std::formatter for it. The easiest way is to inherit from an existing formatter: then you get its whole spec language for free, and you only write format.

C++ A custom formatter

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.

Writing a formatter with your own parse function, for custom spec letters, is possible too; you'll see it in Operator Overloading, alongside operator<< for streams.

Building strings efficiently

std::format returns a new string each time. When you assemble text in pieces, two relatives avoid extra allocations:

  • std::format_to(out, fmt, args...) writes through an output iterator, for example std::back_inserter(str) to append to an existing string.
  • std::formatted_size(fmt, args...) tells you how many characters the result will have; std::format_to_n writes at most n characters into a fixed buffer.
C++
std::string csv;
for (int row = 1; row <= 3; ++row) {
    std::format_to(std::back_inserter(csv), "{},{:.1f}\n", row, row * 1.5);
}
// csv == "1,1.5\n2,3.0\n3,4.5\n"
std::println("{}", std::formatted_size("{}-{}", 10, 200));   // 6

The stream way: <iomanip>

Code written before C++20, and code that writes to std::ostream objects, formats with manipulators from <iomanip>. You need to read it fluently, so here is the mapping:

std::format Stream manipulator Sticky?
{:>10} / {:<10} std::setw(10) + std::right / std::left setw resets after one value; left/right stay
{:*>10} std::setfill('*') stays
{:.2f} std::fixed << std::setprecision(2) stays
{:x} / {:#x} std::hex / + std::showbase stays
{:+} std::showpos stays
{} of bool std::boolalpha (otherwise 1/0) stays

The "sticky" column is the trap: most manipulators change the stream's state permanently, so a std::hex in one function silently changes every number printed afterward.

C++ iomanip and its sticky flags

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.

I/O Streams in Depth covers streams fully. For new code, prefer std::format and std::println: the formatting lives in the format string, applies to one value, and can't leak.

What about printf? You'll see std::printf("%5.2f\n", x) in older and C-flavored code. It works, and GCC checks its format strings with -Wall, but it can't print std::string or your own types, and a mismatched specifier is undefined behavior. std::println("{:5.2f}", x) does the same job safely. C and C++ compares them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::println("[{:*^7}]", "ab"); print?

    ^ centers the value in a width of 7 using * as fill. With 5 fill characters to place, 2 go on the left and 3 on the right.
  2. 2. What does std::format("{:#06x}", 255) return?

    adds the 0x prefix, and 0 pads with zeros after the prefix up to a total width of 6: 0x00ff.

  3. 3. Why does std::string f = "{}"; std::println(f, 1); fail to compile?

    Format strings are parsed and checked at compile time. A runtime std::string can't be checked, so you must opt in with std::vformat (or std::runtime_format in C++26).
  4. 4. With C++23, what does std::println("{}", std::vector<std::string>{"a", "b"}); print?

    Containers print in brackets, and strings inside them use the debug format with quotes so element boundaries are visible.
  5. 5. After std::cout << std::hex << 255; what does a later std::cout << 16; print?

    std::hex is sticky. It stays in effect until you switch back with std::dec, so 16 prints as hexadecimal 10.

Summary

  • std::format returns a string; std::print/std::println write it out (to stdout, stderr or a stream). Format strings are checked at compile time.
  • Spec order: {arg:fill align sign # 0 width .precision L type}. Width is a minimum; <, >, ^ align; any fill character works.
  • Integers: x, X, o, b, c; # adds prefixes; 0 pads after the sign and prefix.
  • Floats print the shortest exact form by default; use .Nf, e, g for fixed looks. Precision on strings truncates.
  • C++23 formats containers, maps, pairs and tuples; n drops brackets, {::spec} formats elements; ? gives quoted debug output.
  • Specialize std::formatter<T> (inheriting from an existing one is easiest) to format your own types.
  • <iomanip> manipulators do the same for streams, but most are sticky; prefer std::format in new code.

Next: Converting Between Strings and Numbers, where you'll parse user text into numbers safely and quickly.