命名空间
变体
操作

std::ostrstream::str

来自 cppreference.cn
< cpp‎ | io‎ | ostrstream
char* str();
(在 C++98 中弃用)
(在 C++26 中移除)

返回指向缓冲区起点的指针,并在之后冻结缓冲区。 有效地调用 rdbuf()->str()

目录

[编辑] 参数

(无)

[编辑] 返回值

指向关联的 std::strstreambuf 中缓冲区起点的指针;如果无缓冲区可用,则为 null 指针。

注意

在调用 str() 并将结果用作 C 字符串之前,流缓冲区必须以空字符结尾。 常规输出(例如使用 stream << 1.2)不会存储空终止符,它必须显式附加,通常使用操纵符 std::ends

在调用 str() 之后,动态流将变为冻结状态。 在退出创建此 ostrstream 对象的作用域之前,需要调用 freeze(false)。 否则,析构函数将泄漏内存。 此外,一旦到达已分配缓冲区的末尾,对冻结流的额外输出可能会被截断,这可能会使缓冲区未以空字符结尾。

[编辑] 示例

#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 的公共成员函数) [编辑]