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-charN$可選,指定使用第N個參數(注意,要么所有指示符都加此參數,要么都不加)
接下來的參數可以參數printf的指示符,只是format為其中的flags添加了'_'和'='標志,用於指出內部對齊和居中對齊。
設置打印規則,它是printf參數的一個補充,只是為了更直觀點。
形式為:%|spec|如:%|1$+5|表示顯示第一個參數,顯示正負號,寬度為5
簡單的位置標記
形式為:%N%簡單地聲明顯示第N個參數,優點是比較直觀而且不用指定類型。
轉載:http://www.cnblogs.com/lzjsky/archive/2011/05/05/2037327.html
