共用方式為


字串和 I/O 格式化 (現代 C++)

C++ iostreams 可進行格式化的字串 I/O。 例如,下列程式碼示範如何先取消儲存目前狀態然後再重設,設定 cout 將整數格式化為十六進位的輸出,因為一旦狀態格式傳遞至 cout,會保持這種方式直到變更為止,而不只是針對一個程式碼行。

#include <iostream>
#include <iomanip>
 
using namespace std;
 
int main() 
{
    ios state(nullptr);
 
    cout << "The answer in decimal is: " << 42 << endl;
 
    state.copyfmt(cout); // save current formatting
    cout << "In hex: 0x" // now load up a bunch of formatting modifiers
        << hex 
        << uppercase 
        << setw(8) 
        << setfill('0') 
        << 42            // the actual value we wanted to print out
        << endl;
    cout.copyfmt(state); // restore previous formatting
}

這在許多情況下都完全難以處理。 或者,您可以使用 Boost C++ 程式庫中的 Boost.Format,即使它是非標準的。 您可以從 Boost 網站下載任何 Boost 程式庫。

Boost.Format 的一些優點是:

  • 安全:類型安全,並針對錯誤擲回例外狀況 -- 例如,有太少或太多項目的規格。

  • 可延伸的:適用於可以進行資料流處理的任何類型。

  • 方便:標準 Posix 和類似的格式字串。

雖然 Boost.Format 是建置在 C++ iostreams 基礎上,是安全且可擴充的,但並非效能最佳化。 當您需要效能最佳化時,請考慮使用 C 的 printfsprintf,這是既快速又容易使用的。 然而,它們無法擴充或有安全性弱點。(安全版本存在,但是產生些微的效能損失。 如需詳細資訊,請參閱 printf_s、_printf_s_l、wprintf_s、_wprintf_s_lsprintf_s、_sprintf_s_l、swprintf_s、_swprintf_s_l)。

下列程式碼示範部分提升格式化功能。

    string s = str( format("%2% %2% %1%\n") % "world" % "hello" );
    // s contains "hello hello world"  
 
    for( auto i = 0; i < names.size(); ++i )
        cout << format("%1% %2% %|40t|%3%\n") % first[i] % last[i] % tel[i];
    // Georges Benjamin Clemenceau             +33 (0) 123 456 789
    // Jean de Lattre de Tassigny              +33 (0) 987 654 321

請參閱

參考

<iostream>

<limits>

<iomanip>

其他資源

歡迎回到 C++ (現代 C++)

C++ 語言參考

C++ 標準程式庫參考