- 语法:
boost::format(format-string)%arg1%arg2%…%argN;
- format与printf的区别:
printf(s, x1, x2);
cout << format(s) % x1 % X2;
使用size()成员函数,得到format字符串的字符个数
使用str()成员函数,将format字符串转化为string字符串
3.三种常用的书写风格:
<1>简单风格
cout<<format("%1% %2% %3% %2% %1% \n") %"11"%"22"%"333";
//It prints : "11 22 333 22 11 \n"
<2>Posix-Printf风格
cout << format("(x,y) = (%1$+5d,%2$+5d) \n") % -23 % 35;
//It prints : "(x,y) = ( -23, +35) \n"
<3>经典风格
cout <<format("writing %s,x=%s:%d-th step\n") %"toto" % 40.23% 50;
//It prints:"writing toto, x=40.23 : 50-th step \n"
printf格式说明符:
- 不同于c printf,这里还支持位置参数
Note:在同一个format string中,位置格式说明符不能与非位置格式说明符混用
- 一个格式说明符spec有如下格式:
[ N$ ] [ flags ] [ width ] [ . precision ] [ argument-type ] conversion-specifier
N$:位置格式说明符,指出格式说明符应用于第N个参数
如果没有,参数是按顺序对应格式说明符的
flags:
‘-’:左对齐
‘=’:中心对齐
‘_’:内部对齐
‘+’:显示数字的正负号
‘#’:显示小数点
‘0’:对齐时用0填充
’ ':如果字符串不以+或-开头,则在转换的字符串前插入空格
width:为转化后的字符串设置一个最小宽度
precision: 设置流的精度,如一个float型数据,设置数字个数的最大值
argument-type:为了处理可变参数;hh,h,l,ll,j,z,and L are recognized
conversion-specifier:
b:输出布尔字符串
p,x:输出十六进制
o:输出八进制
a:十六进制指数计数
e:科学浮点格式
f:固定浮点格式
g:通用,默认为浮点格式
X,A,E,F,G:大写输出
d,i,u:输出十进制
s,S:输出字符串
c,C:输出单个字符
%:输出%字符
#include<boost/format.hpp>
#include<opencv/core/core.hpp>
boost::format fmt("./data/%s%d.%s");
cv::imread((fmt%"color"%1%"png").str(),-1); //读入图像./data/color1.png
示例:
boost::format类提供了类似C语言里’printf’功能的格式化输出能力,当然功能更强大。
所需头文件:
#include <boost/format.hpp>
示例代码:
#include <iostream>
#include <string>
#include <boost/format.hpp>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 使用%序号%的方式给出指示符, 后面用%连接对应的数据。
cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50 << endl;
// 输出:writing toto, x=40.23 : 50-th try
// 可以延迟使用,顺序不必一致
boost::format fmter("%2% %1%");
fmter % 36;
fmter % 77;
cout << fmter << endl;
// 输出:77 36
// 可重用
fmter % 12;
fmter % 24;
cout << fmter << endl;
// 输出:24 12
// 可直接转成字符串
std::string s = fmter.str();
std::string s2 = str( boost::format("%2% %1% %2% %1%")%"World"%"Hello");
cout << s << endl << s2 << endl;
// 输出:
// 24 12
// Hello World Hello World
// 可以使用printf指示符
cout << boost::format("%3.1f - %.2f%%") % 10.0 % 12.5 << endl;
// 输出:10.0 - 12.50%
// printf指示符里使用N$指定使用第几个参数
cout << boost::format("%2$3.1f - %1$.2f%%") % 10.0 % 12.5 << endl;
// 输出:12.5 - 10.00%
cin.get();
return 0;
}
boost::format里的指示符语法大致有三大类:
- 继承并强化自printf的格式化字符串
形式为:[ N$ ] [ flags ] [ width ] [ . precision ] type-char
N$可选,指定使用第N个参数(注意,要么所有指示符都加此参数,要么都不加)
接下来的参数可以参数printf的指示符,只是format为其中的flags添加了’_‘和’='标志,用于指出内部对齐和居中对齐。 - 设置打印规则,它是printf参数的一个补充,只是为了更直观点。
形式为:%|spec|
如:%|1$+5|表示显示第一个参数,显示正负号,宽度为5 - 简单的位置标记
形式为:%N%
简单地声明显示第N个参数,优点是比较直观而且不用指定类型。

368

被折叠的 条评论
为什么被折叠?



