Boost 的 format 函式庫提供了一套靈活而強大的字串格式化機制,語法既借鑑了 C 風格的 printf,又保留了 C++ iostream 的型別安全與可擴充性。以下是一個完整的示範程式:
#include <iostream>
#include <iomanip>
#include <cassert>
#include "boost/format.hpp"
// 兩個自訂命名空間,用來引入一些好用的名稱:
namespace MyNS_ForOutput {
using std::cout; using std::cerr;
using std::string;
using std::endl; using std::flush;
using boost::format;
using boost::io::group;
}
namespace MyNS_Manips {
using std::setfill;
using std::setw;
using std::hex ;
using std::dec ;
// gcc-2.95 未定義下面這幾個
// using std::showbase ;
// using std::left ;
// using std::right ;
// using std::internal ;
}
int main(){
using namespace MyNS_ForOutput;
using namespace MyNS_Manips;
std::cout << format("%|1$1| %|2$3|") % "Hello" % 3 << std::endl;
// 重新排序(Reordering):
cout << format("%1% %2% %3% %2% %1% \n") % "o" % "oo" % "O"; // 'simple' 風格
// 印出 "o oo O oo o \n"
cout << format("(x,y) = (%1$+5d,%2$+5d) \n") % -23 % 35; // Posix-Printf 風格
// 不重新排序:
cout << format("writing %s, x=%s : %d-th step \n") % "toto" % 40.23 % 50;
// 印出 "writing toto, x=40.23 : 50-th step \n"
cout << format("(x,y) = (%+5d,%+5d) \n") % -23 % 35;
cout << format("(x,y) = (%|+5|,%|+5|) \n") % -23 % 35;
cout << format("(x,y) = (%|1$+5|,%|2$+5|) \n") % -23 % 35;
// 以上三種寫法結果相同,都印出 "(x,y) = ( -23, +35) \n"
// 透過 'group' 使用操縱器(manipulators):
cout << format("%2% %1% %2%\n") % 1 % group(setfill('X'), hex, setw(4), 16+3) ;
// 印出 "XX13 1 XX13\n"
// printf 指示符的 type-flag 也可用來傳遞格式化選項:
cout << format("_%1$4d_ is : _%1$#4x_, _%1$#4o_, and _%1$s_ by default\n") % 18;
// 印出 "_ 18_ is : _0x12_, _ 022_, and _18_ by default\n"
// 取得字串值:
std::string s;
s= str( format(" %d %d ") % 11 % 22 );
assert( s == " 11 22 ");
// -----------------------------------------------
// %% 會印出 '%'
cout << format("%%##%#x ") % 20 << endl;
// 印出 "%##0x14 "
// -----------------------------------------------
// 強制引數數量必須正確
// 引數過多時,餵入多餘引數會丟出例外:
try {
format(" %1% %1% ") % 101 % 102;
// 格式字串只參照了一個引數(用了兩次),並非兩個引數,
// 因此傳入兩個引數就是錯誤
}
catch (boost::io::too_many_args& exc) {
cerr << exc.what() << "\n\t\t***別擔心,這是刻意安排的\n";
}
// 請求結果時引數不足,同樣會丟出例外:
try {
cerr << format(" %|3$| ") % 101;
// 即使沒用到 %1$ 和 %2$,你也應該提供三個引數
}
catch (boost::io::too_few_args& exc) {
cerr << exc.what() << "\n\t\t***別擔心,這是刻意安排的\n";
}
cerr << "\n\nEverything went OK, exiting. \n";
return 0;
}
Hello 3 o oo O oo o (x,y) = ( -23, +35) writing toto, x=40.23 : 50-th step (x,y) = ( -23, +35) (x,y) = ( -23, +35) (x,y) = ( -23, +35) XX13 1 XX13 _ 18_ is : _0x12_, _ 022_, and _18_ by default %##0x14 boost::too_many_args: format-string refered to less arguments than were passed ***別擔心,這是刻意安排的 boost::too_few_args: format-string refered to more arguments than were passed ***別擔心,這是刻意安排的 Everything went OK, exiting.