Link to home
Create AccountLog in
Avatar of josgood
josgoodFlag for United States of America

asked on

std::stringstream Insertion & Extraction

The following program inserts strings into a stringstream and then extracts from the beginning of the stringstream.  I'm happy that it works this way, but don't understand why.  Speaking in file terms, I'd guess stringstream maintains separate read and write positions.

How does stringstream achieve this behavior?

#include <iostream>
#include <sstream>

int main() {
      std::stringstream ss;
      ss << "abc" << "def" << std::endl;
      std::cout << ss.str();
      // displays abcdef on std::cout
      return 0;
}

Avatar of MURUGESAN N
MURUGESAN N
Flag of India image

Here stringstream is still the stream.
This can be seen here:
http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Demonstratestringstreams.htm

The operators << or >>
does the same way w.r.to cout or cin respectively
and the output(display screen) being replaced with stringstream.
Avatar of evilrix
The stringstream class is actually derived from 2 interfaces, istringstream and ostringstream and each contains its own stream pointer. The istringstream contains a [p]ut pointer so when you write to the stream this gets incremented but the ostringstreams [g]et pointer does not (this stays positioned at the start) so when you read you start reading from the start. You can position these pointers independently using seekp() and seekg() and you get get their positions independently using tellp() and tellg().

http://www.cplusplus.com/reference/iostream/stringstream/
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
You could see a stringstream as a sort of queue for characters. You push characters on the stream at the back, and you pop them from the front. If you don't know what a queue is, then this analogy will probably not make sense, but hey, I can give it a try :)
>> then this analogy will probably not make sense
Except streams are random access, queues (if implemented correctly) are not :)
I was referring to the behavior he observed. And I did say "sort of a queue".
>> I was referring to the behavior he observed.
Ok, but I wanted to make sure there wasn't a confusion -- you're clarification ensures this :)
Avatar of josgood

ASKER

>> ...2 interfaces, istringstream and ostringstream and each contains its own stream pointer
Evilrix, this directly answers my question.  

>>[p]ut pointer...[g]et pointer...seekp() and seekq()...tellp() and tellg()
This clarifies another confusion.  Now this makes sense.

Good reference.  That page also makes it clear.

Thank you.
>> Thank you.
No worries josgood. As always, it's a pleasure to help :)