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

mslot picture mslot · Apr 7, 2009 · Viewed 10.3k times · Source

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.

Answer

bayda picture bayda · Apr 8, 2009
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.