std::format — safe string formatting (C++20).
1#include <format>23std::string s = std::format("Hello, {}! You are {}.", "Alice", 30);45// Formatting specifiers6std::cout << std::format("{:.2f}", 3.14159); // 3.147std::cout << std::format("{:10}", "hi"); // " hi"8std::cout << std::format("{:05d}", 42); // 000429std::cout << std::format("{:#x}", 255); // 0xff
vs printf/snprintf:
Custom formatters:
1template <>2struct std::formatter<MyType> {3 auto format(const MyType& v, auto& ctx) {4 return std::format_to(ctx.out(), "({},{})", v.x, v.y);5 }6};