Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 983
mathematician1975 Avatar asked Jul 12 '12 19:07

mathematician1975


1 Answers

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();
like image 57
Kerrek SB Avatar answered Sep 30 '22 01:09

Kerrek SB