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;
-
}