116
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?

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Alex F
  • 42,307
  • 41
  • 144
  • 212

1 Answers1

239
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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 8
    +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 07:47
  • 2
    This answer is worth looking too: http://stackoverflow.com/a/624291/142239 – Siu Ching Pong -Asuka Kenji- Oct 09 '13 at 03: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 02 '13 at 15:42
  • 1
    @ThanasisPapoutsidakis Yes, the scope { } will destroy any local variables in the loop after each iteration, so each foo is a totally new instance. Will an STL implementation have an internal cache to reuse the memory for old string streams and other types? These days probably not as everything is multithreaded optimisations such as this and copy on write (COW) are less useful. – pilkch Feb 24 '16 at 03:50
  • 2
    `#define sstr(x) (oss.str(""),oss.clear(),oss << x, oss.str())` allows terse code (used for test cases and the like): `name=sstr("pow" << i << ":" << j);` – Erik Aronesty Jul 19 '17 at 17:40
  • Regarding the use of a new ostringstream, if you have a non-global locale to use, calling `imbue` for every new stringstream might degrade performance. Regadring @BoPersson's comment, a stringstream doesn't have so much state that a call to `clear` and a call to `str` is a big hit. – Spencer Jan 11 '19 at 17:52