std::format — type-safe string formatting (Python-like syntax).
1#include <format>23// Basic formatting4std::string s = std::format("Hello, {}! You are {}.", "Alice", 25);56// Positional arguments7std::cout << std::format("{1} {0}", "world", "hello");89// Number formatting10std::cout << std::format("{:.2f}", 3.14159); // 3.1411std::cout << std::format("{:#x}", 255); // 0xff12std::cout << std::format("{:08d}", 42); // 000000421314// Alignment15std::cout << std::format("{:>10}", "right"); // " right"16std::cout << std::format("{:<10}", "left"); // "left "17std::cout << std::format("{:^10}", "center"); // " center "1819// Custom type20struct Point { int x, y; };21template<>22struct std::formatter<Point> : std::formatter<std::string> {23 auto format(const Point& p, auto& ctx) const {24 return std::format_to(ctx.out(), "({}, {})", p.x, p.y);25 }26};27std::cout << std::format("{}", Point{1, 2}); // (1, 2)
Advantages over printf/iostream: