简体   繁体   English

使用str()和rdbuf()打印出字符串流

[英]Printing out a stringstream using str() and rdbuf()

When I have: 当我有:

std::ostringstream oss("Hello");

Why does this work: 为什么这样做:

std::cout << oss.str();

but this doesn't print anything: 但这不会打印任何内容:

std::cout << oss.rdbuf();

Reading the definition of operator<<(std::ostream&, std::streambuf*) say that it will print characters from the buffer. 阅读operator<<(std::ostream&, std::streambuf*) ,它会打印缓冲区中的字符。 Does oss.rdbuf() not contain anything? oss.rdbuf()不包含任何内容吗?

This issue is related to the fact that here, oss is ostringstream object ( ostringstream is output stream so its destination is to write to it and not to read from it ) and to fact how streams manage its internal buffer. 此问题与以下事实有关: oss在这里是ostringstream对象( ostringstream是输出流,因此其目标是向其写入而不是从其中读取 ),以及与流如何管理其内部缓冲区有关。

You can change 你可以改变

std::ostringstream oss("Hello");

to

std::istringstream oss("Hello");  // or std::stringstream oss("Hello");

and it will work as expected. 它将按预期工作。 Alternatively use 替代使用

std::cout << oss.rdbuf()->str(); // this will print a copy of all buffer content

Example: 例:

#include <iostream>
#include <sstream>

int main() {
    std::ostringstream oss("Hello");
    std::istringstream oss2("Hello");
    cout << oss.rdbuf()->str() << endl;  // prints "Hello"
    cout << oss2.rdbuf();                // prints "Hello"
    return 0;
}

Objects of ostringstream class use a string buffer that contains a sequence of characters. ostringstream类的对象使用包含一系列字符的字符串缓冲区。 This sequence of characters can be accessed directly as a string object, using member str. 可以使用成员str作为字符串对象直接访问此字符序列。 That explains first part. 这就解释了第一部分。

std::ostringstream oss("Hello");
std::cout << oss.str(); // works

The rdbuf returns pointer to the associated streambuf object, which is charge of all input/output operations. rdbuf返回指向关联的streambuf对象的指针,该对象负责所有输入/输出操作。 Thus, you need to use str() again to print the contents as in: 因此,您需要再次使用str()来打印内容,如下所示:

std::cout << oss.rdbuf()->str();

instead of: 代替:

std::cout << oss.rdbuf();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM