clearing a stringstream

W

William Payne

How do you get rid the contents in a std::stringstream? I'm using one in a
for loop to format some status messages which I print to the screen. The
stringstream member function clear() only clears flags (bits) in the stream,
right? I solved it by declaring the stringstream inside the loop body even
though I have need of another stringstream just after the loop. So for each
iteration the constructor of the stringstream will be executed. Is this how
I should go about it? *looks at sprintf()*

/ WP
 
J

John Harrison

William Payne said:
How do you get rid the contents in a std::stringstream? I'm using one in a
for loop to format some status messages which I print to the screen. The
stringstream member function clear() only clears flags (bits) in the stream,

Right.

I solved it by declaring the stringstream inside the loop body even
though I have need of another stringstream just after the loop. So for each
iteration the constructor of the stringstream will be executed. Is this how
I should go about it? *looks at sprintf()*

Do this instead

std::stringstream buf;
....
buf.str(std::string()); // set contents of string stream

john
 
W

William Payne

John Harrison said:
Do this instead

std::stringstream buf;
...
buf.str(std::string()); // set contents of string stream

john

Thanks John, I will do that instead.

/ WP
 
S

Shiju Rajan

Doesn't flush work for clearing the contents ........stringstream derives
from ostream and this class has a flush function to clear the buffer.
 
W

William Payne

Shiju Rajan said:
Doesn't flush work for clearing the contents ........stringstream derives
from ostream and this class has a flush function to clear the buffer.

No, everything is still there after a call to flush().

/ WP
 
J

John Harrison

Shiju Rajan said:
Doesn't flush work for clearing the contents ........stringstream derives
from ostream and this class has a flush function to clear the buffer.

No it doesn't. Flushing the buffer means committing the contents of the
buffer to the final destination. In the case of fstream this means writing
the buffer to a file. But in the case of stringstream the final destination
is the string object held internally in the stringstream object. So flushing
the buffer (if it did anything) would mean writing to the string held
internally in the stringstream object. Its that string that William is
trying to empty, not write to.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top