名稱空間
變體
操作

std::ostrstream::str

來自 cppreference.com
< cpp‎ | io‎ | ostrstream
char* str();
(C++98 起棄用)
(C++26 中移除)

返回緩衝區起始處的指標,並凍結它。實際上呼叫 rdbuf()->str()

目錄

[編輯] 引數

(無)

[編輯] 返回值

指向關聯的 std::strstreambuf 中緩衝區起始處的指標,如果無可用緩衝區則為 null 指標。

注意

在使用 str() 的結果作為 C 字串之前,流緩衝區必須以 null 字元終止。常規輸出(例如 stream << 1.2)不會儲存 null 終止符,必須顯式附加,通常使用操縱符 std::ends

呼叫 str() 後,動態流會被凍結。在退出建立此 ostrstream 物件的範圍之前,需要呼叫 freeze(false),否則解構函式將導致記憶體洩漏。此外,對凍結流的額外輸出一旦達到分配緩衝區的末尾,可能會被截斷,這可能導致緩衝區未以 null 字元終止。

[編輯] 示例

#include <iostream>
#include <strstream>
 
int main()
{
    std::ostrstream dyn; // dynamically-allocated output buffer
    dyn << "Test: " << 1.23; // not adding std::ends to demonstrate append behavior
    std::cout << "The output stream holds \"";
    std::cout.write(dyn.str(), dyn.pcount()) << "\"\n"; 
    // the stream is now frozen due to str()
    dyn << " More text" << std::ends;
    std::cout << "The output stream holds \"";
    std::cout.write(dyn.str(), dyn.pcount()) << "\"\n";
    dyn.freeze(false);
}

可能的輸出

The stream holds "Test: 1.23"
The stream holds "Test: 1.23 More "

另請參閱

將緩衝區標記為凍結並返回輸入序列的起始指標
(std::strstreambuf 的公共成員函式) [編輯]