C++ Format String using boost::format

如果你只想寫純粹的 C,那你可以忽略這篇的資訊了,因為 sprintf 之類的 function 大概就可以滿足你了。那為什麼還要提到 C++?我想 C++ 的 string 對於程式設計者是美好的,因為我們不用擔心 buffer 到底需要多長,我們可能是無腦的利用 operator += 去操作這個字串,並利用提供的 substring 等 function 快速的開發軟體。

但在我甚少的 C++ 開發經驗中,我總覺得透過 operator += 以及 stringstream 等東西,並沒有辦法像 sprintf 那樣直覺而優雅的將變數置換至字串當中。

就以 Windows 常見的 INI 格式來說,我們如果要輸出一個 AppName,像是 [MyApp],可能的作法是

    output += '[';
    output += strSection;
    output += ']';

這似乎比傳統的 sprintf 要顯得複雜的多,也顯得不好閱讀……

    sprintf(output, "[%s]", strSection);

現在你可以考慮 boost::format

    std::string output = boost::str(boost::format("[%s]") % strSection);

讓你寫的 C++ 能有 sprintf 的優雅性,又不必太過於擔心 buffer 的操作。

至於一些 manipulators,與詳細的 formatting 的用法,就請你自己去看一下官方的說明吧。此外,我覺得 python 的 formatting string 能吃 dictionary 也實在是很棒,而且很優雅的寫法。

    print "%(key)s %(key)s" % {'key': 'yoyo'}

在 boost::format 雖然只能這樣寫,但也聊勝於無了。

    std::cout < < boost::format("%1% %1%") % "yoyo";

某些情況下,你會考慮用 boost::lexical_cast,而捨棄 stringstream 等,不過也容許我提醒你一下,boost 會讓 object 變得肥上不少,至於怎麼取捨,就端看你的選擇了。

This entry was posted in C++, Programming and tagged , . Bookmark the permalink.

9 Responses to C++ Format String using boost::format

  1. pointnone says:

    也可以直接用 C 的寫法做下去
    sprintf(output, “[%s]“, strSection.c_str());

  2. Hubert says:

    重點是希望 output 是一個不用自己管理 buffer 的 string 啦 :p

  3. pointnone says:

    唔,這樣平常一樣是用 string 在做,只有 output 時把他轉回來

  4. Hubert says:

    很漂亮的作法,非常感謝 :)

    btw, 我想我們應該是同事(笑)

  5. fr3@K says:

    @Hubert
    不用客氣, 留了公司的 email, 歡迎有機會到 15 樓找我聊天.

    Happy hacking~

  6. lucky17 says:

    咦? 不是可以寫成:
    output = ‘[' + strSection + ']‘;

    不太懂 @@”

  7. sypan says:

    笨頭哥太強大了!
    找資料都找的到你的部落格!

  8. Hubert says:

    @sypan
    不過好久沒寫了 XD 看來你們那邊應該常常用 boost 了 :p

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>