2024年5月30日发(作者:)
C++ format 函数用法
在C++中,我们经常需要将一些数据格式化输出或者进行字符串拼接操作。
C++11标准开始,C++引入了一个新的函数库——format库,可以更加方便的进
行字符串格式化操作。在本文中,我们将介绍C++ format函数的基本用法,及
其一些常见的格式化操作。
1. 包含头文件
在使用C++ format函数之前,我们需要包含头文件 format,如下所示:
#include
1. 基本语法
C++ format函数的基本语法如下:
std::string formatted_str = std::format(format_str, );
其中,format_str是格式化字符串,是可变参数模板,可以传入任意
数量的参数。函数返回一个std::string类型的格式化后的字符串。
例如:
std::string str = std::format("My name is {}, I am {} years old.",
"Tom", 25);
上述代码将格式化字符串中的 {} 替换成后面传入的参数值,得到一个字符串
My name is Tom, I am 25 years old.。
1. 字符串拼接
C++ format函数可以方便地实现字符串拼接操作。使用类似于上面的语法方
式,将需要拼接的字符串传入函数中,得到最终的字符串。例如:
std::string str = std::format("{} {} {}", "hello", "world", "!");
上述代码将三个字符串按照顺序拼接起来,得到一个字符串 hello world !。
1. 格式化输出数字
除了字符串拼接,C++ format函数也可以用来格式化数字的输出。例如,我们
可以设置输出的小数位数:
std::string str = std::format("pi is {:.3f}", 3.1415926);
上述代码将数字 3.1415926 按照三位小数的精度进行输出,得到字符串 pi is
3.142。
1. 对齐格式
C++ format函数还支持对输出结果进行对齐格式处理。例如,我们可以将右对
齐格式应用到数字输出中:
std::string str = std::format("{:>5d}", 123);
上述代码将数字123右对齐,并且总长度为5,得到字符串 123。
1. 自定义格式串
除了上述常见的格式化操作,C++ format函数还支持自定义格式串。例如,我
们可以使用{}包裹格式控制信息,将自定义格式应用到变量输出中:
double pi = 3.1415926;
std::string str = std::format("pi is {:+.2e}, in hex it is {:#x}",
pi, static_cast
上述代码使用自定义格式串,将变量 pi 格式化输出为科学计数法,并将 pi
转为十六进制格式输出,得到字符串 pi is +3.14e+00, in hex it is 0x3,其
中,+表示正号,0表示填充字符,2表示小数点后位数,e表示使用科学计数
法输出,#表示使用十六进制输出,并输出0x前缀。
1. 格式化宽度(占位符)
C++ format函数还支持设置宽度,即设置输出结果的固定宽度。例如,我们可
以将以下代码:
std::string str = std::format("{}", "hello");
修改为:
std::string str = std::format("{:10}", "hello");
这样一来,输出结果就会加上2个空格,总共输出10个字符,如下所示:
hello
如果我们将宽度设置为负数,就会左对齐输出,如下所示:
std::string str = std::format("{:<10}", "hello");
输出结果如下:
hello
1. 格式化字符
C++ format函数还支持将字符按照指定格式输出。例如:
std::string str = std::format("{:c}", 'A');
上述代码将字符 A 按照 ASCII 码输出,得到字符串 65。
1. 格式化指针地址
如果我们想要使用C++ format函数输出指针地址,需要使用 {} 来包装输出格
式,而不是使用 %p,例如:
int *p = new int(10);
std::string str = std::format("The address of the pointer is: {:#x}",
reinterpret_cast
输出结果如下:
The address of the pointer is: 0x55e80d9c11c0
到这里,我们就掌握了C++ format函数的基本用法。使用C++ format函数,
我们可以更加方便地进行字符串格式化操作,避免了手动拼接字符串的繁琐过
程。


发布评论