views:

881

answers:

2

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.

+2  A: 

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

anon
Oh. I have never head about that book!! Sounds like a good book, because, I think that I kinda like the complexity around C++ streams.
mslot
It is good book - if you are interested in streams. Which frankly, few C++ programmers (me included) are.
anon
But in my example, shouldnt the rdbuf() and rdbuf()->str() return the same thing because of the first parameter of getline is a call-by-reference?
mslot
If we think theoretically of course and look away from the fact that streambuf "behaves in an extremely counterintuitive way".
mslot
Link to Langer and Kreft page 72: http://tinyurl.com/LnKpg72
C.W.Holeman II
+3  A: 
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.

bb
Oh. The fact that I have'nt looked it up in one of me expensive C++ books is that Im on a vacation, so I only have google and I couldnt find a site explaining the operator<< behaviour in a way that I understood. I actually thought that getline removed tokens with the delim from the stream.
mslot
I didn't use one of expensive C++ books. I just undertsood that this behavior is not rbuf() specified and start looked in standard for this overloading operator<<.
bb
http://ra.dkuug.dk/jtc1/sc22/open/n2356/ - free C++ standard draft
bb
Remove characters from reading string buffer is slow operation - and obviously don't used. Thank you for interest task:)
bb
bb, looking in the standard :) I have such standard at home. I'm on a vacation and dont got it with me. I have read the declarations for the iostream operators, but that didnt tell me how it worked. I guess I was lost in google. But thanks for the link!!
mslot