原文地址
boost::format類提供了類似C語(yǔ)言里'printf'功能的格式化輸出能力,當(dāng)然功能更強(qiáng)大。
所需頭文件:
#include <boost/format.hpp>
示例代碼:
#include <iostream>
#include <string>
#include <boost/format.hpp>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 使用%序號(hào)%的方式給出指示符, 后面用%連接對(duì)應(yīng)的數(shù)據(jù)。
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
// 可直接轉(zhuǎn)成字符串
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$指定使用第幾個(gè)參數(shù)
cout << boost::format("%2$3.1f - %1$.2f%%") % 10.0 % 12.5 << endl;
// 輸出:12.5 - 10.00%
cin.get();
return 0;
}
boost::format里的指示符語(yǔ)法大致有三大類:
繼承并強(qiáng)化自printf的格式化字符串
形式為
:[ N$ ] [ flags ] [ width ] [ . precision ] type-char N$可選,指定使用第N個(gè)參數(shù)(注意,要么所有指示符都加此參數(shù),要么都不加)
接下來(lái)的參數(shù)可以參數(shù)printf的指示符,只是format為其中的flags添加了'_'和'='標(biāo)志,用于指出內(nèi)部對(duì)齊和居中對(duì)齊。
設(shè)置打印規(guī)則,它是printf參數(shù)的一個(gè)補(bǔ)充,只是為了更直觀點(diǎn)。
形式為
:%|spec|
如:%|1$+5|表示顯示第一個(gè)參數(shù),顯示正負(fù)號(hào),寬度為5
簡(jiǎn)單的位置標(biāo)記
形式為
:%N% 簡(jiǎn)單地聲明顯示第N個(gè)參數(shù),優(yōu)點(diǎn)是比較直觀而且不用指定類型。