Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear ostringstream [duplicate]

Tags:

c++

stream

     ostringstream s;      s << "123";     cout << s.str().c_str() << endl;      // how to clear ostringstream here?     s << "456";     cout << s.str().c_str() << endl; 

Output is:

 123 123456 

I need:

 123 456 

How can I reset ostringstream to get desired output?

like image 249
Alex F Avatar asked Mar 13 '11 07:03

Alex F


People also ask

How do you clear a SS?

For best results, spray the surface of the metal with several sprays of vinegar, and then pull out another clean microfiber cloth to wipe the metal. The vinegar will clean the surface and remove all traces of other compounds and cleaners. Once the stainless steel is clean and dry, start polishing.

How do you clear a Stringstream object?

You can easily clear the content of a StringStream object by using the predefined ss. clear() function. The function will erase the data in the buffer and make the object empty. The below code demonstrates how to clear StringStream in C++.


1 Answers

s.str(""); s.clear(); 

The first line is required to reset the string to be empty; the second line is required to clear any error flags that may be set. If you know that no error flags are set or you don't care about resetting them, then you don't need to call clear().

Usually it is easier, cleaner, and more straightforward (straightforwarder?) just to use a new std::ostringstream object instead of reusing an existing one, unless the code is used in a known performance hot spot.

like image 144
James McNellis Avatar answered Sep 21 '22 23:09

James McNellis