c++中的boost::format使用方法

这段时间一直在学习SLAM方面的东西,偶尔遇到boost,在这里做个笔记以方便日后使用。

 

format主要是用来格式化std::string字符串以及配合std::cout代替C语言printf()

使用format需要#include"boost/format.hpp"
 

boost::format的格式一般为:

boost::format( "format-string ") % arg1 % arg2 % ... % argN ;

注意这里没有示例对象,format-string代表需要格式化的字符串,后面用重载过的%跟参数

 

1.format占位符的使用

 

std::cout<<boost::format("%1% \n %2% \n %3%" )%"first"%"second"%"third";

上面例子中%X%表示占位符,%1%就是第一个占位符,%2%就是第二个,后面类推,再后面的%"xxx"就对应着每个占位符,也就是说如果我们写成:

std::cout<<boost::format("%2% \n %1% \n %3%" )%"first"%"second"%"third";

将会输出

second

 first

 third

当然我们也可以分开写,比如:

    boost::format fmt("%2% \n %1% \n %3%" );
    fmt %"first";
    fmt %"second";
    fmt %"third";

2.format的交互形式

标题不好,凑合看吧。

 

我们还可以很方便的把格式化后的实例赋给std::string,如:

boost::format fmt("%1%")%"helloworld"; 

std::string st=fmt.str();

你可以这样通过变量格式化,这与int a=5;printf("%d",a);是一个道理,不同的是format是对字符的格式化而不包含输出。

int a=5;

int b=6;

std::cout<< boost::format("%1% %2%" )%a%b;

3.format格式化

格式化语法为: [ N$ ] [ flags ] [ width ] [ . precision ] type-char

有两种版本:C语言和.net版本,我这里就复制粘贴了一段:

//传统c语言风格

cout << boost::format("\n\n%s"

"%1t 十进制 = [%d]\n"

"%1t 格式化的十进制 = [%5d]\n"

"%1t 格式化十进制,前补'0' = [%05d]\n"

"%1t 十六进制 = [%x]\n"

"%1t 八进制 = [%o]\n"

"%1t 浮点 = [%f]\n"

"%1t 格式化的浮点 = [%3.3f]\n"

"%1t 科学计数 = [%e]\n"

) % "example :\n" % 15 % 15 % 15 % 15 % 15 % 15.01 % 15.01 % 15.01 << endl;

//.net的风格

cout << boost::format("%1%"

"%1t 十进制 = [%2$d]\n"

"%1t 格式化的十进制 = [%2$5d]\n"

"%1t 格式化十进制,前补'0' = [%2$05d]\n"

"%1t 十六进制 = [%2$x]\n"

"%1t 八进制 = [%2$o]\n"

"%1t 浮点 = [%3$f]\n"

"%1t 格式化的浮点 = [%3$3.3f]\n"

"%1t 科学计数 = [%3$e]\n"

) % "example :\n" % 15 % 15.01 << endl;

 

boost::format使用还是很不错的,不过效率不尽人意,所以你需要在效率和使用方便两个方面取舍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值