Skip to content

std::format (C++20)

TL;DR

A type-safe printf alternative—format strings using {} placeholders, checks argument count at compile time, and supports custom type formatting.

<format>

Core API Cheat Sheet

OperationSignatureDescription
Format stringstd::format(fmt, args...)Returns formatted string
Format to outputstd::format_to(out, fmt, args...)Outputs to iterator
Format to bufferstd::formatted_size(fmt, args...)Pre-calculates output length
Format to stdout(C++23) std::print(fmt, args...)Outputs directly to standard output
Positional argsstd::format("{0} {1}", a, b)References arguments by index
Width/precisionstd::format("{:>10.2}", v)Right-aligned, width 10, precision 2
Custom formattingtemplate<> struct formatter<T>Specialize formatter to support custom types

Minimal Example

cpp
#include <format>
#include <iostream>
#include <string>

int main() {
    // Basic replacement
    std::string s = std::format("The answer is {}.", 42);
    // s == "The answer is 42."

    // Alignment and width
    int x = 42;
    std::cout << std::format("{:>10}", x) << '\n'; // "        42"

    // Type-specific formatting (hex)
    std::cout << std::format("{:#x}", 255) << '\n'; // "0xff"
}

Embedded Applicability: Medium

  • Replaces printf, eliminating runtime crash risks from mismatched format strings and argument types.
  • Replaces std::stringstream, avoiding heap allocation overhead.
  • Checks argument count at compile time, but full compile-time validation of format specifiers requires std::format in C++23.
  • Flash overhead may be significant (formatting engine code size); evaluate for resource-constrained devices.
  • The {fmt} library can be used as a backport for C++11 and later.

Compiler Support

GCCClangMSVC
131719.29

See Also


Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05