文档目录

为什么需要它?

// printf:类型不安全,不检查 %d 和参数是否匹配
printf("int: %d, str: %s\n", 42); // ❌ 少传一个参数 → 未定义行为!

// ostringstream:性能差,写起来啰嗦
std::ostringstream oss;
oss << "int: " << 42 << ", str: " << "hello";
std::string s = oss.str(); // 多个 << 拼接,每个 << 有一次虚函数调用

// format:编译期检查,性能最高
std::string s = std::format("int: {}, str: {}", 42, "hello");
// 如果花括号个数和参数个数不匹配 → 编译错误!

性能对比

// 格式化 100 万次
std::format("value = {}", x);                   // ~30ms
snprintf(buf, 64, "value = %d", x);             // ~50ms
ss << "value = " << x; ss.str();                // ~150ms

为什么 format 最快?

  • printf 运行时解析格式字符串(检查 %d、%f 等)。
  • ostringstream 每次 << 调用虚函数,多次分配内存。
  • format 在编译期解析 {},运行时只做简单的替换和参数格式化。

常用格式控制

std::format("{:.2f}", 3.14159);       // "3.14"(保留两位小数)
std::format("{:>10}", "hello");       // "     hello"(右对齐,宽度 10)
std::format("{:<10}", "hello");       // "hello     "(左对齐)
std::format("{:^10}", "hello");       // "  hello   "(居中)
std::format("{:0>6}", 42);            // "000042"(零填充)
std::format("{:x}", 255);             // "ff"(十六进制小写)
std::format("{:X}", 255);             // "FF"(十六进制大写)
std::format("{:b}", 255);             // "11111111"(二进制)