所需头文件:
#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;
-
-
-
- boost::format fmter("%2% %1%");
- fmter % 36;
- fmter % 77;
- cout << fmter << endl;
-
-
-
- fmter % 12;
- fmter % 24;
- cout << fmter << endl;
-
-
-
- std::string s = fmter.str();
- std::string s2 = str( boost::format("%2% %1% %2% %1%")%"World"%"Hello");
-
- cout << s << endl << s2 << endl;
-
-
-
-
-
- cout << boost::format("%3.1f - %.2f%%") % 10.0 % 12.5 << endl;
-
-
-
- cout << boost::format("%2$3.1f - %1$.2f%%") % 10.0 % 12.5 << endl;
-
-
- 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个参数,优势是比较直观并且不用指定类型。