c++kquote>C++20引入std::format,提供类型安全、高性能的字符串格式化,支持占位符、对齐控制、自定义类型及编译期检查,替代printf和ostringstream,需包含头文件并启用-std=c++20。

C++20 引入了 std::format,这是一个现代化、类型安全且高性能的字符串格式化库,用来替代传统的 printf 和 ostringstream 等方式。它借鉴了 Python 的 str.format() 和 Rust 的 format! 语法,使用起来更直观、更安全。
基本用法:std::format 格式化字符串
std::format 使用类似于 Python 的占位符语法 {} 或 {index} 来插入变量。
示例:
#include #include 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}:居中对齐 {:06}:数字补零到6位 {:.2f}:浮点数保留2位小数示例:
std::cout << std::format("|{:8}|{:^8}|n", "left", "right", "center");// 输出: |left | right| center |std::cout << std::format("{:05}", 42); // 输出: 00042std::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;};templatestruct std::formatter { 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),就可以放心使用。注意包含头文件 ,并启用 -std=c++20 编译选项。
以上就是C++20的std::format库怎么用_C++字符串格式化新特性详解的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1481136.html
微信扫一扫
支付宝扫一扫