Boost:格式化输出--Format

boost::format类提供了相似C语言里'printf'功能的格式化输出能力,功能更强大。

所需头文件:

#include <boost/format.hpp>

示例代码:

  1. #include <iostream>
  2. #include <string>
  3. #include <boost/format.hpp>
  4.   
  5. using namespace std;
  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8.     // 使用%序号%的方式给出指示符, 后面用%链接对应的数据。
  9.     cout << boost::format("writing %1%,  x=%2% : %3%-th try") % "toto" % 40.23 % 50 << endl;
  10.     // 输出:writing toto,  x=40.23 : 50-th try
  11.    
  12.     // 能够延迟使用,顺序没必要一致
  13.     boost::format fmter("%2% %1%");
  14.     fmter % 36;
  15.     fmter % 77;
  16.     cout << fmter << endl;
  17.     // 输出:77 36
  18.    
  19.     // 可重用
  20.     fmter % 12;
  21.     fmter % 24;
  22.     cout << fmter << endl;
  23.     // 输出:24 12
  24.   
  25.     // 可直接转成字符串
  26.     std::string s = fmter.str();
  27.     std::string s2 = str( boost::format("%2% %1% %2% %1%")%"World"%"Hello");
  28.   
  29.     cout << s << endl << s2 << endl;
  30.     // 输出:
  31.     // 24 12
  32.     // Hello World Hello World
  33.   
  34.     // 能够使用printf指示符
  35.     cout << boost::format("%3.1f - %.2f%%") % 10.0 % 12.5  << endl;
  36.     // 输出:10.0 - 12.50%
  37.   
  38.     // printf指示符里使用N$指定使用第几个参数
  39.     cout << boost::format("%2$3.1f - %1$.2f%%") % 10.0 % 12.5  << endl;
  40.     // 输出:12.5 - 10.00%
  41.   
  42.     cin.get();
  43.     return 0;
  44. }
 

boost::format里的指示符语法大体有三大类:

继承并强化自printf的格式化字符串

    形式为:[ N$ ] [ flags ] [ width ] [ . precision ] type-char
    N$可选,指定使用第N个参数(注意,要么全部指示符都加此参数,要么都不加)
    接下来的参数能够参数printf的指示符,只是format为其中的flags添加了'_'和'='标志,用于指出内部对齐和居中对齐。

设置打印规则,它是printf参数的一个补充,只是为了更直观点。

    形式为:%|spec|
    如:%|1$+5|表示显示第一个参数,显示正负号,宽度为5

简单的位置标记

    形式为:%N%
    简单地声明显示第N个参数,优势是比较直观并且不用指定类型。
 
 
转载:http://www.cnblogs.com/lzjsky/archive/2011/05/05/2037327.html
相关文章
相关标签/搜索