format库提供了一个把参数格式化到一个字符串格式的类,
就像printf所做的,但是有两个主要的不同:
format将参数发送给合适的stream,所以它是完全类型安全的并且自然地支持所有的用户自定义的类型。
在format强类型转换中省略号不能被正确使用,需要不确定参数的函数被连续调用操作符%来替代。
- 基本用法
-
#include<iostream> -
#include<iomanip> -
#include<cassert> - #include"boost/format.hpp"
-
-
namespaceMyNS_ForOutput{ -
using std::cout;using std::cerr; -
using std::string; -
using std::endl;using std::flush; -
-
using boost::format; -
using boost::io::group; -
} -
-
namespaceMyNS_Manips{ -
using std::setfill; -
using std::setw; -
using std::hex; -
using std::dec; -
} -
-
int main() -
{ -
usingnamespaceMyNS_ForOutput; -
usingnamespaceMyNS_Manips; -
-
std::cout<< format("%|1$1| %|2$3|")%"Hello"%"world"<< std::endl; -
//Hello world -
-
//字符串格式化 -
std::string s; -
s= str( format(" %d %d ")%11%22); -
std::cout<< s<< std::endl; -
-
//其他进制格式化 -
cout<< format("%#x ")%20<< endl; -
//0x14 -
cout<< format("%#o ")%20<< endl; -
//024 -
cout<< format("%#d ")%20<< endl; -
//20 -
-
-
//异常 -
// the format-string refers to ONE argument, twice. not 2 arguments. -
// thus giving 2 arguments is an error -
// Too much arguments will throw an exception when feeding the unwanted argument : -
try{ -
format(" %1% %1% ")%101%102; -
-
} -
catch(boost::io::too_many_args& exc){ -
cerr<< exc.what()<< endl; -
} -
-
-
// Too few arguments when requesting the result will also throw an exception : -
// even if %1$ and %2$ are not used, you should have given 3 arguments -
try{ -
cerr<< format(" %|3$| ")%101; -
} -
catch(boost::io::too_few_args& exc){ -
cerr<< exc.what()<<"\n\t\t***Dont worry, that was planned\n"; -
} -
return0; -
}
本文介绍 Boost.Format 库的使用方法,该库提供了一种类型安全的字符串格式化方式,支持各种内置类型和用户自定义类型的格式化输出。文章通过示例展示了如何进行字符串、不同进制数的格式化,并讨论了格式化过程中可能出现的异常情况。

368

被折叠的 条评论
为什么被折叠?



