
C++20 引入了 std::format,这是一个现代化、类型安全且高性能的字符串格式化库,用来替代传统的 printf 和 ostringstream 等方式。它借鉴了 Python 的 str.format() 和 Rust 的 format! 语法,使用起来更直观、更安全。
std::format 使用类似于 Python 的占位符语法 {} 或 {index} 来插入变量。
#include <format>
#include <iostream>
int main() {
std::string name = "Alice";
int age = 30;
std::string result = std::format("Hello, {}! You are {} years old.", name, age);
std::cout << result << '\n';
// 输出: Hello, Alice! You are 30 years old.
}
支持按位置引用:
std::string s = std::format("{1} is {0} years old.", age, name);
// 输出: Alice is 30 years old.
可以在大括号中添加格式说明符,控制输出宽度、对齐、填充等。
立即学习“C++免费学习笔记(深入)”;
语法:{:[fill][align][width][.precision][type]}
常用格式选项:
{:>10}:右对齐,总宽10{:<10}:左对齐,总宽10{:^10}:居中对齐{:06}:数字补零到6位{:.2f}:浮点数保留2位小数
std::cout << std::format("|{:<8}|{:>8}|{:^8}|\n", "left", "right", "center");
// 输出: |left | right| center |
std::cout << std::format("{:05}", 42); // 输出: 00042
std::cout << std::format("{:.3f}", 3.14159); // 输出: 3.142
std::format 原生支持整数、浮点数、字符串、布尔值、指针等常见类型。
例如布尔值默认输出为 true/false,也可用 {:d} 转为 1/0:
std::format("{}", true) // "true"
std::format("{:d}", true) // "1"
对于自定义类型,需要特化 std::formatter 模板:
struct Point {
double x, y;
};
template<>
struct std::formatter<Point> {
constexpr auto parse(auto& ctx) { return ctx.begin(); }
auto format(const Point& p, auto& ctx) const {
return std::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
// 使用
std::format("Position: {}", Point{1.23, 4.56});
// 输出: Position: (1.2, 4.6)
相比 printf,std::format 是类型安全的,编译器能在编译期检查格式字符串与参数的匹配性(部分实现支持)。
相比 std::ostringstream,它通常更快,因为避免了多次函数调用和动态内存分配。
还支持运行时格式字符串(类似 printf),但建议尽量使用字面量以获得最佳优化。
如果需要仅计算格式化后长度,可使用 std::formatted_size;若要写入已有缓冲区,可用 std::format_to。
auto size = std::formatted_size("Value: {}", 42); // 返回所需大小
char buffer[64];
std::format_to(buffer, "Hello, {}", "World");
基本上就这些。std::format 让 C++ 字符串处理变得更现代、简洁又高效。只要编译器支持 C++20(如 GCC 13+、Clang 14+、MSVC 2022),就可以放心使用。注意包含头文件 <format>,并启用 -std=c++20 编译选项。
以上就是C++20的std::format库怎么用_C++字符串格式化新特性详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号