How to clear ostringstream

Alex F picture Alex F · Mar 13, 2011 · Viewed 81.7k times · Source
    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?

Answer

James McNellis picture James McNellis · Mar 13, 2011
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.