Why is stringstreams rdbuf() and str() giving me different output?

大憨熊 提交于 2019-12-09 13:24:48

问题


I have this code,

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;
}

Giving me this output

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

ss.rdbuf() : hej med dig

But why is that? Is that because of ostreams definition of operator<str() gives me different output. In my eyes the output should be the same even if I have used getline.


回答1:


ss.rdbuf()->str();

Returns copy of all buffer content.

What doing std::cout << ss.rdbuf();?

See description for

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

It read character by character from buffer and write them to ostream, until eof/fail on writing/exception occurs.

You already have read one word from buff. Now it read rest part.




回答2:


To quote from the bible on C++ stream I/O, Langer and Kreft, calling str() on a stream buffer (i.e. the thing returned by rdbuf()) "behaves in an extremely counterintuitive way" (page 72 in my edition). For the full story, you will have to read the book.

If you don't get a satisfactory answer here, try the usenet group:

http://groups.google.com/group/comp.lang.c++.moderated



来源:https://stackoverflow.com/questions/727737/why-is-stringstreams-rdbuf-and-str-giving-me-different-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!