How to clear ostringstream

C++Stream

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex FView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow