This question already has an answer here:
-
How do you clear a stringstream variable?
8 answers
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?
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.