How to clear streamstring buffer?

I have a streamstring in two loops and I am writing my RAM. So, how to clean the steam jet buffer? This simplifies:

stringstream ss (stringstream::in | stringstream::out); for() { for() { val = 2; ss << 2; mystring = ss.str(); // my stuff } // Clear the buffer here } 

He wrote 2, then 22, then 222 ... I tried .clear () or .flush (), but it is not. So how am I doing this?

+4
source share
3 answers

The obvious solution is to use a new stringstream every time, for example:

 for (...) { std::stringstream ss; for (...) { // ... } } 

This is the stringstream way stringstream was designed to be used. (Also: do you really want stringstream , or just ostringstream ?)

+7
source

Install ss.str(""); when you want to remove extra characters (Edit: thank you).

Use .clear() if your thread has set error flags during the previous conversion.

+5
source

If you are using C ++ 0x:

 ss.swap(stringstream()); 

Visual Studio 2010 (SP1) supports it.

If you are not using C ++ 0x:

 ss.seekp(0); ss.seekg(0); ss.str(""); ss.clear(); 

It will not clear the memory, but you can use your stringstream object as it would be empty earlier.

+3
source

All Articles