c++ - 为什么 stringstreams rdbuf() 和 str() 给我不同的输出?

标签 c++ std stringstream getline sstream

我有这个代码,

int main()
{
    std::string st;
    std::stringstream ss;
    ss<<"hej hej med dig"<<std::endl;

    std::getline(ss,st,' ');
    std::cout <<"ss.rdbuf()->str() : " << ss.rdbuf()->str();
    std::cout <<"ss.rdbuf() : " << ss.rdbuf();
    return 0;
}

给我这个输出

ss.rdbuf()->str() : hej hej med dig

ss.rdbuf() : hej med dig

但这是为什么呢?是因为 ostreams 对 operator

最佳答案

ss.rdbuf()->str();

返回所有缓冲区内容的拷贝。

在做什么std::cout << ss.rdbuf();

查看说明

basic_ostream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb);

它从缓冲区逐个字符地读取并将它们写入ostream,直到eof/写入失败/异常发生。

你已经读过 buff 中的一个词。现在它读取其余部分。

关于c++ - 为什么 stringstreams rdbuf() 和 str() 给我不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/727737/

相关文章:

c++ - 来自 Visual Studio 的 std 文件中的错误

c++ - 如何访问 vector 值 std::vector <cv::Point2f> pto

c++ - 将 "this"参数显式传递给方法调用

c++ - 添加额外字符时 stringstream 的 putback 失败

c++ - isdigit() 无法将 "1"识别为数值

c++ - C++ 内部的字符编码?

c++ - ffmpeg 问题

c++ - 为什么我的文件会出现损坏的输出?

c++ - 为什么 C++ StringStream 跳过输入文件中的第一个数字,但显示其余数字?

c++ - 与字符串流不同的插入位置