4

I have a streamstring in two loops and it is burning my RAM. So how to clear properly the buffer of a steamstring? It is like that to simplify :

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

It wrote 2 then 22 then 222... I tried .clear() or .flush() but it is not that. So how I do this?

4
  • 1
    I would put the stringstream into the loop. Commented Jun 16, 2011 at 10:25
  • If I put std::stringstream ss; in a loop it will creat many ss in the RAM and will burn it no? Or it will delete ss at the end of his loop because it is created in a loop? (It feel a noob question here :) but I am! ) Commented Jun 16, 2011 at 10:52
  • it is created and destroyed as the program loops. BTW, what do you mean with "burn the RAM"? Commented Jun 16, 2011 at 13:49
  • My app grow in 30s at 2Go and crash. "it is created and destroyed as the program loops" I didn't know that, I thought it create many ss and they would destroy at the end of the function/app/object. Thank you Commented Jun 16, 2011 at 14:03

3 Answers 3

8

The obvious solution is to use a new stringstream each time, e.g.:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

I use it here to change a float in a string and put this string in a big other string. What is the best to do that? And if I put std::stringstream ss; in a loop it will creat many ss in the RAM no?
std::ostringstream ss; ss << theDouble; theString += ss.str(); And if the stringstream is in the loop, there will still only be one in memory at a time.
7

Set ss.str(""); when you want to clear out the excess characters (Edit: thank you).

Use .clear() if your stream has set any error flags in the process of the prior conversion.

5 Comments

It is usually not enough. You should also use seekp(0) and seekg(0), too.
@Naszta I was able to do it without the seekp/seekg portion after setting the string and then clearing the stream.
@jonsca: in this case it depends on the implementation. I had many issue on it before. (I develop multi platform, I don't remember which implementation had/has this issue.)
For future reference, this is covered in Scott Meyers books on C++ (which I recommend).
4

If you use C++0x:

ss.swap(stringstream()); 

Visual Studio 2010 (SP1) supports it.

If you don't use C++0x:

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

It won't clear the memory, but you could use your stringstream object as it would be empty before.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.