一、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
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;
四、異常處理
一般寫法:
{
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::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;
五、還有其它一些功能,但暫時感覺派不上用處,就不去深究了。