Skip to content

std::format (C++20)

In a Nutshell

A type-safe replacement for printf -- format strings with {} placeholders, compile-time argument count checking, and support for custom type formatting.

#include <format>

Core API Quick Reference

OperationSignatureDescription
Format stringstring format(fmt, args...)Returns the formatted string
Format to outputvoid vformat_to(out_it, fmt, args)Output to an iterator
Format to buffersize_t formatted_size(fmt, args...)Pre-compute output length
Format to stdout(C++23) void print(fmt, args...)Direct output to standard output
Positional arguments"{0} {1} {0}"Reference arguments by index
Width/precision"{:>10.2f}"Right-align, width 10, precision 2
Custom formattingtemplate<> struct formatter <T>Specialize std::formatter to support custom types

Minimal Example

cpp
// Standard: C++20
#include <format>
#include <iostream>
#include <string>

int main() {
    std::string s = std::format("Hello, {}!", "world");
    std::cout << s << "\n"; // Hello, world!

    int version = 2;
    double pi = 3.14159265;
    std::cout << std::format("v{}. pi={:.2f}", version, pi) << "\n";
    // v2. pi=3.14

    // Positional arguments
    std::cout << std::format("{0} + {0} = {1}", 3, 6) << "\n";
    // 3 + 3 = 6
}

Embedded Applicability: Medium

  • Replaces printf, eliminating the risk of runtime crashes from format-string/argument type mismatches
  • Replaces std::stringstream, avoiding heap allocation overhead
  • Compile-time argument count checking; full compile-time format specifier validation requires C++23's std::is_constant_evaluated
  • Flash overhead may be significant (formatting engine code size); evaluate for extremely resource-constrained devices
  • The {fmt} library can serve as a C++11-compatible fallback

Compiler Support

GCCClangMSVC
131719.29

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress