#include <boost/format.hpp> #include <iostream> using namespace boost; using namespace std; // 格式输出控制,(类似c++准准库中的sprintf) // int main() { // format库的几种用法 //------------------------------------------ // 第一种: // 最接近printf() cout<< "First: " << format("%s: %d + % d = %d/n")%"sum"%1%2%(1+2); // format 重载了%操作符类似<<操作符 // result: sum: 1 + 2 =3 // 第二种: // 在format对象中用%X%指定X是第几个参数 format fmt1("(%1% + %2%)*%2% = %3%/n"); // %1% 接收第一个参数, %2% 接收第二个参数, %3%接收第三个参数 fmt1 %2 %5; // 第一,二个参数 fmt1 %((2+5)*5); // 第三个参数,参数不一定像第一种方法直接植入,可以分次完成但参数的总数量不能少 cout<< "Second: " << fmt1.str(); // str()是获取格式化后的字符串,不负责清空 // result: (2 + 5)*5 = 50; // 第三种: // 带格式化选项(和printf一样) format fmt3("%05d %-8.3f %10s %05X/n"); cout<< "Third: " <<fmt3 %62 %3.14159f %123456789 %48; // 第四种: // 在对象构造函数字符串添加管道符,用于美观 format fmt4("%|05d| %|-8.3f| %|10s| %|05X|/n"); cout<< "Fourth: " << fmt4 %62 %3.14159f %123456789 %48; // 高级应用: format fmtOther("%1% %2% %3% %2% %1%"); cout<< "Other normal: " << fmtOther %1 %2 %3 <<endl; // 插入值 %1%对应第一个参数,%2%第二个, %3%第三个 fmtOther.bind_arg(2, 10); // 将第二个参数固定为10,即使使用clear也一样 cout<< "Other bind_arg: " << fmtOther %1 %3 <<endl; // 插入值时忽略%2%,直接跳到下一个%X% // group, modify_item 略 //----------------------------- // 与printf的比较: //----------------------------- // printf是函数,format是类 // printf不进行类形检查,format进行类型安全检查 // printf速度是format的2到5倍 // format个人还不太习惯 getchar(); return 0; }