[prog] C++ stringstream or something else?

Robert J. Hansen rjh at sixdemonbag.org
Tue Apr 15 11:30:04 EST 2003


> This seems to be OK but when I print it I get only the value of the first 
> variable printed.  I am guessing that it is because it gets to a "\0".

I read your next message, so I won't give you the preferred solution
because you've already found it.  :)  But I figured an explanation of
why it doesn't work is in order.

When dealing with text streams, spaces delimits variables.  (This
behavior can be changed.)  So if you feed in "Foo", "Bar", 38 and "Quux"
to a stringstream, the stringstream's internal state will read "Foo Bar
38 Quux".

Upon reading out of the stream, you do "strstream_var >> string_var"
and, instead of "Foo Bar 38 Quux", you only get "Foo".  Because it'll
only read in until it sees whitespace, at which point it'll stop.  :)

You can feed in strings with embedded spaces without any problem, but
upon pulling them back out, it'll all be tokenized.

stringstream sstr;
string foobar("Foo Bar");
string bar;
sstr << foobar; // feed in "Foo Bar"
sstr >> foobar; // foobar now contains "Foo"
sstr >> bar;    // bar now contains "Bar"

-- 
Robert J. Hansen <rjh at sixdemonbag.org>



More information about the Programming mailing list