Z
ZHANK
编程在线教程C++ 教程std::format 格式化
C++20/23 与惯用法

std::format 格式化

format 替代 printf/sprintf、占位符 {}、格式说明、chrono 时间格式化

std::format 格式化

std::format(C++20)是 printf 的类型安全替代——编译期检查、可扩展、快。

学完本章你将: 掌握 format 替代 printf、占位符、chrono 时间格式化。


基本用法

cpp
#include <format>
#include <iostream>

int main() {
    int age = 25;
    double score = 92.5;
    std::string name = "小明";

    // 基本格式化
    std::cout << std::format("姓名: {}, 年龄: {}, 成绩: {:.1f}\n",
                             name, age, score);
    // 姓名: 小明, 年龄: 25, 成绩: 92.5

    // 位置索引
    std::cout << std::format("{1} 岁, {0}\n", name, age);
    // 25 岁, 小明

    // 命名参数(C++20 fmt 库风格,标准库未完全支持)
    // 用 {fmt} 库获得命名参数支持
}

格式说明

cpp
// 整数
std::format("{:d}", 42);      // "42"(十进制)
std::format("{:x}", 255);     // "ff"(十六进制)
std::format("{:08d}", 42);    // "00000042"(宽度 8,补零)

// 浮点
std::format("{:.2f}", 3.14159);  // "3.14"
std::format("{:e}", 1000.0);     // "1.000000e+03"

// 对齐
std::format("{:>10}", "hi");  // "        hi"(右对齐)
std::format("{:<10}", "hi");  // "hi        "(左对齐)
std::format("{:^10}", "hi");  // "    hi    "(居中)

// 二进制
std::format("{:b}", 42);      // "101010"(C++20)

chrono 时间格式化

cpp
#include <chrono>

auto now = std::chrono::system_clock::now();

std::cout << std::format("{:%Y-%m-%d %H:%M:%S}", now);
// 2024-07-23 14:30:00