http://www.cnblogs.com/wuerping/archive/2005/04/21/142308.html

概述

     std::string是个很不错的东东,但实际使用时基本在每个程序里都会遇到不愉快的事情:格式化字符串。我 甚至由于这个原因在代码里引入平台有关的MFC,ATL等本来不需要在项目中使用的一些重量级的框架,就为了能轻松的做格式化字符串 :-) 。曾尝试过将ATL::CString的format函数提取出来使用,但ATL::CString的底层调用了windows独有函数,无法跨越平台。 当然,现在有了boost::format,我们不用再担心了。boost::format重载了'%'操作符,通过多次调用'%'操作符就能将参数非常 方便格式化成字符串,并实现了ATL::CString和C#中的string两者的格式化字符串功能。除了语法刚开始感觉到怪异,功能足以让人感觉到兴 奋!

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

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


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

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


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

四、异常处理

 一般写法:

浅尝boost之format try


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

浅尝boost之format // boost::io::all_error_bits selects all errors
浅尝boost之format
// boost::io::too_many_args_bit selects errors due to passing too many arguments.
浅尝boost之format
// boost::io::too_few_args_bit selects errors due to asking for the srting result before all arguments are passed
浅尝boost之format

浅尝boost之format boost::format my_fmt(
const std::string & f_string)
;

 
五、还有其它一些功能,但暂时感觉派不上用处,就不去深究了。

相关文章: