Take the 2-minute tour ×
    ostringstream s;

    s << "123";
    cout << s.str().c_str() << endl;

    // how to clear ostringstream here?
    s << "456";

Output is:


I need:


How can I reset ostringstream to get desired output?

share|improve this question

1 Answer 1

up vote 71 down vote accepted

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.

share|improve this answer
+1 for creating a fresh stream each time. Streams can have lots of internal state. Resetting all of that takes at least as much code as the stream constructor. –  Bo Persson Mar 13 '11 at 7:47
This answer is worth looking too: stackoverflow.com/a/624291/142239 –  Siu Ching Pong -Asuka Kenji- Oct 9 '13 at 3:35
related question: when declared in a loop, will ostringstream be destructed and constructed on each iteration, or I need to use this method? For example, for (int i=0; i<100; ++i) { std::ostringstream foo; foo << "bar"; std::cout << foo.str() << " ";}. Will this print: bar bar bar [...] or bar barbar barbarbar [...]? –  Thanasis Papoutsidakis Nov 2 '13 at 15:42

Your Answer


