boost::format

来源:互联网 发布:nginx 使用内存缓冲 编辑:程序博客网 时间:2024/06/05 05:47

boost::format重载了'%'操作符,通过多次调用'%'操作符就能将参数非常方便格式化成字符串,并实现了ATL::CString和C#中的string两者的格式化字符串功能。

一、boost::format工作的方式 
  
 基本的语法,boost::format( format-string ) % arg1 % arg2 % ... % argN 
  
 下面的例子说明boost::format简单的工作方式  
   
 

// 方式一 
 cout << boost::format("%s") % "输出内容" << endl; 
 
 // 方式二 
 std::string s; 
 s = str( boost::format("%s") % "输出内容" ); 
 cout << s << endl; 
 
 // 方式三 
 boost::format formater("%s"); 
 formater % "输出内容"; 
 std::string s = formater.str(); 
 cout << s << endl; 
 
 // 方式四 
 cout << boost::format("%1%") % boost::io::group(hex, showbase, 40) << endl; 


二、boost::format实际使用的实例 
  
 格式化语法: [ N$ ] [ flags ] [ width ] [ . precision ] type-char  
   
 

// ATL::CString风格 
 cout << boost::format("\n\n%s" 
 "%1t 十进制 = [%d]\n" 
 "%1t 格式化的十进制 = [%5d]\n" 
 "%1t 格式化十进制,前补'0' = [%05d]\n" 
 "%1t 十六进制 = [%x]\n" 
 "%1t 八进制 = [%o]\n" 
 "%1t 浮点 = [%f]\n" 
 "%1t 格式化的浮点 = [%3.3f]\n" 
 "%1t 科学计数 = [%e]\n" 
 ) % "example :\n" % 15 % 15 % 15 % 15 % 15 % 15.01 % 15.01 % 15.01 << endl; 
 
 // C#::string风格 
 cout << boost::format("%1%" 
 "%1t 十进制 = [%2$d]\n" 
 "%1t 格式化的十进制 = [%2$5d]\n" 
 "%1t 格式化十进制,前补'0' = [%2$05d]\n" 
 "%1t 十六进制 = [%2$x]\n" 
 "%1t 八进制 = [%2$o]\n" 
 "%1t 浮点 = [%3$f]\n" 
 "%1t 格式化的浮点 = [%3$3.3f]\n" 
 "%1t 科学计数 = [%3$e]\n" 
 ) % "example :\n" % 15 % 15.01 << endl; 
 
 
输出结果 
/* 
example : 
 十进制 = [15] 
 格式化的十进制 = [ 15] 
 格式化十进制,前补'0' = [00015] 
 十六进制 = [f] 
 八进制 = [17] 
 浮点 = [15.010000] 
 格式化的浮点 = [15.010] 
 科学计数 = [1.501000e+001] 
*/
 


三、boost::format新的格式说明符 
  
 %{nt} 
 当n是正数时,插入n个绝对制表符 
 cout << boost::format("[%10t]")  << endl; 
  
 %{nTX} 
 使用X做为填充字符代替当前流的填充字符(一般缺省是一个空格) 
 cout << boost::format("[%10T*]")  << endl;  

四、异常处理 

 一般写法: 

 try 
 
 cout << boost::format("%d%d") % 1 << endl; 
 }
 
 catch(std::exception const & e) 
 
 cout << e.what() << endl; 
 
 // 输出内容: 
 
// boost::too_few_args: format-string refered to more arguments than were passed 
 }
 


 boost::format的文档中有选择处理异常的办法,不过个人感觉实用性可能不强,下面是文档中的例子  
  

 // boost::io::all_error_bits selects all errors 
 
// boost::io::too_many_args_bit selects errors due to passing too many arguments. 
 
// boost::io::too_few_args_bit selects errors due to asking for the srting result before all arguments are passed 
 
 boost::format my_fmt(const std::string & f_string) 
 
 using namespace boost::io; 
 format fmter(f_string); 
 fmter.exceptions( all_error_bits ^ ( too_many_args_bit | too_few_args_bit ) ); 
 return fmter; 
 }
 
 cout << my_fmt(" %1% %2% \n") % 1 % 2 % 3 % 4 % 5;

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

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

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

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

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

简单的位置标记

    形式为:%N%
    简单地声明显示第N个参数,优点是比较直观而且不用指定类型。


0 0