现在的位置: 首页 > 综合 > 正文

boost之format库,格式化输出

2018年10月05日 ⁄ 综合 ⁄ 共 674字 ⁄ 字号 评论关闭

示例代码:

#include <iostream>
#include <string>
using namespace std;

#include <boost/format.hpp>
using namespace boost;


int main(int argc, char*argv[])
{
	//顺序不必一致
	format fmter("%2% %1%");
	fmter % 100;
	fmter % 200;
	cout<<"fmter:"<<fmter<<endl;

	//可重用
	fmter % 11;
	fmter % 22;
	cout<<"fmter:"<<fmter<<endl;

	//可直接转为字符串
	string s = fmter.str();
	cout<<"s:"<<s.c_str()<<endl;

	string s2 = str(format("%2% %1% %2% %1%") % "World" % "Hello");
	cout<<"s2:"<<s2.c_str()<<endl;


	//可以使用printf指示符
	cout<<format("%3.1f, %d") % 3.2 % 8<<endl;


	//其他用法
	cout<<format("(x,y) = (%+5d, %+5d)") % -23 % 35<<endl;
	cout<<format("(x,y) = (%|+5|, %|+5|)") % -23 % 35<<endl;
	cout<<format("(x,y) = (%1$+5d, %2$+5d)") % -23 % 35<<endl;
	cout<<format("(x,y) = (%|1$+5|, %|2$+5|)") % -23 % 35<<endl;

	return 0;
}

输出结果:


抱歉!评论已关闭.