std::strstream::str
来自 cppreference.cn
char* str(); |
(C++98 中已弃用) (C++26 中已移除) |
|
返回指向缓冲区开头的指针,并在冻结缓冲区后返回。 有效地调用 rdbuf()->str()。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
指向关联的 std::strstreambuf 中缓冲区开头的指针,如果无缓冲区可用则为 null 指针。
注解
在调用 str()
并将结果用作 C 字符串之前,流缓冲区必须以空字符结尾。 常规输出(例如使用 stream << 1.2)不会存储空终止符,必须显式追加,通常使用操纵符 std::ends。
在调用 str()
之后,动态流变为冻结状态。 在退出创建此 strstream 对象的作用域之前,需要调用 freeze(false)
。 否则析构函数将泄漏内存。 此外,一旦到达已分配缓冲区的末尾,对冻结流的额外输出可能会被截断,这可能导致缓冲区未以空字符结尾。
[编辑] 示例
运行此代码
#include <iostream> #include <strstream> int main() { std::strstream 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 的公共成员函数) |