How do you clear a std::ostringstream instance so it can be reused?

mathematician1975 picture mathematician1975 · Jul 12, 2012 · Viewed 12.9k times · Source

Possible Duplicate:
How to reuse an ostringstream?

I have been using std::ostringstream to convert float and int values to strings but I cannot find anyway to reuse an instance. To illustrate what I mean here is the following along with the methods that I have tried to use to clear the stream

 #include <iostream>
 #include <sstream>
 using namespace std;

 int main() {
   ostringstream stream;
   stream << "Test";
   cout << stream.str() << endl;  
   stream.flush();                
   stream << "----";
   cout << stream.str() << endl; 
   stream.clear();
   stream << "****";
   cout << stream.str() << endl;
   return 0;
 }

generates output

 Test
 Test----
 Test----****

This is giving me a problem as I am having to create many instances of ostringstream which is wasteful. Clearly clear() and flush() do not do what I need so is there a way to do this? I checked the documentation at http://www.cplusplus.com/reference/iostream/ostringstream/ but there is nothing there that appears to do what I need. Is there a way to reset or clear the stream??

Answer

Kerrek SB picture Kerrek SB · Jul 12, 2012

Use stream.str(""); to make the underlying string an empty one. Better yet, don't reuse objects. In C++ the philosophy is to make an object when you need it and dispose of it when you're done:

{
    std::ostringstream oss;
    oss << 10;
    std::cout << oss.str();
}

{
    std::ostringstream oss;
    oss << 20.5;
    std::cout << oss.str();
}

Or better yet:

std::cout << static_cast<std::ostringstream&>(std::ostringstream() << 10).str();