boost之format

format库提供了一个把参数格式化到一个字符串格式的类,

就像printf所做的,但是有两个主要的不同:

  • format将参数发送给合适的stream,所以它是完全类型安全的并且自然地支持所有的用户自定义的类型。
  • format强类型转换中省略号不能被正确使用,需要不确定参数的函数被连续调用操作符%来替代。
 1 #include <iostream>
 2 #include <iomanip>
 3 #include <cassert>
 4 
 5 #include "boost/format.hpp"
 6  
 7  namespace MyNS_ForOutput {
 8   using std::cout; using std::cerr;
 9   using std::string;
10   using std::endl; using std::flush;
11 
12   using boost::format;
13   using boost::io::group;
14 }
15 
16 namespace MyNS_Manips {
17   using std::setfill;
18   using std::setw;
19   using std::hex ;
20   using std::dec ;
21 }
22 
23 int main()  
24 {  
25     using namespace MyNS_ForOutput;
26     using namespace MyNS_Manips;
27 
28     std::cout << format("%|1$1| %|2$3|") % "Hello" % "world" << std::endl;
29     //Hello world
30     
31     //字符串格式化
32     std::string s;
33     s = str( format(" %d %d ") % 11 % 22 );
34     std::cout << s << std::endl;
35 
36     //其他进制格式化
37     cout << format("%#x ") % 20 << endl;
38     //0x14
39     cout << format("%#o ") % 20 << endl;
40     //024
41     cout << format("%#d ") % 20 << endl;
42     //20
43  
44 
45     //异常
46     // the format-string refers to ONE argument, twice. not 2 arguments.
47     // thus giving 2 arguments is an error
48     // Too much arguments will throw an exception when feeding the unwanted argument :
49     try {
50       format(" %1% %1% ") % 101 % 102;52     }
53     catch (boost::io::too_many_args& exc) { 
54       cerr <<  exc.what() << endl;
55     }
56 
57     
58     // Too few arguments when requesting the result will also throw an exception :
59     // even if %1$ and %2$ are not used, you should have given 3 arguments
60     try {
61       cerr << format(" %|3$| ") % 10162     }
63     catch (boost::io::too_few_args& exc) { 
64       cerr <<  exc.what() << "\n\t\t***Dont worry, that was planned\n";
65     }
66     return 0;  
67 }  

特色用法

#include <iostream>
#include <iomanip>

#include "boost/format.hpp"
int main()  
{  
    using namespace std;
    using boost::format;
    using boost::io::group;

  
    // Simple style of reordering :
    cout << format("%1% %2% %3% %2% %1% \n") % "1" % "2" % "3";
    //12321

    //"%|Nt|"  => N个空格
    vector<string>  names(1, "Marc-Fran鏾is Michel"), 
      surname(1,"Durand"), 
      tel(1, "+33 (0) 123 456 789");

    names.push_back("Jean"); 
    surname.push_back("de Lattre de Tassigny");
    tel.push_back("+33 (0) 987 654 321");

    for(unsigned int i=0; i<names.size(); ++i)
      cout << format("%1%, %2%, %|40t|%3%\n") % names[i] % surname[i] % tel[i];

    /*
    Marc-Fran鏾is Michel, Durand,       +33 (0) 123 456 789
    Jean, de Lattre de Tassigny,        +33 (0) 987 654 321
    */

}  

猜你喜欢

转载自www.cnblogs.com/osbreak/p/9203315.html