sprinfのC++版「boost::format」

C++Builder 2009からBoostが標準添付されて、とても使いやすくなりました。

そのBoostのライブラリの一つ「boost::format」は、sprinfのC++版とも言えるライブラリです。
(The Boost Format library)

printfの書式指定子と同じ書式文字列を使用することができます。
また拡張フォーマットにより%1%で1番目の引数、%2%で2番目の引数を出力できます。

#include <boost/format.hpp>

//formatの生成
boost::format fmter("%1% %2% \n"); //引数は書式文字列
std::cout << fmter % "abc" % "efg"; //=> abc efg

//何度でも取り出せる
std::string s1 = fmter.str(); //メンバ関数str()
std::cout << s1; //=> abc efg

//何度でも取り出せる
std::string s2 = str(fmter); //関数boost::str()
std::cout << s2; //=> abc efg

//並べ替え
std::cout << boost::format("%1% %2% %3% %2% %1% \n") % "11" % "22" % "33";
//=> 11 22 33 22 11

//printf互換
std::cout << boost::format("%05d %x %f %%") % 200 % 255 % 3.33;
//=> 00200 ff 3.330000 %

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください