6

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

Community
  • 1
  • 1
mathematician1975
  • 21,161
  • 6
  • 59
  • 101

2 Answers2

18

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();
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • +1: Was about to say the exact same thing. Although doing `stream.str("");` always felt like a hack to me. – John Dibling Jul 12 '12 at 19:20
  • 4
    Generally agree with your post except for the part that starts with *Or better yet:* and the rest that follows. You couldn't possibly think that is **better**, would you?! – Happy Green Kid Naps Jul 12 '12 at 19:52
  • @HappyGreenKidNaps: It's just an example. Of course you could write `std::cout << 10` and be done with it. If I needed a string, I'd say `std::to_string(10)`, I suppose. – Kerrek SB Jul 12 '12 at 20:21
  • 3
    There's no such thing as "philosophy in C++ to make an object when you need it and dispose when you're done" and there has never been. Using the str("") call is the perfect way of "resetting" the stringstream. It's rather your hint to use static_cast, that is generally predicted to never be used in the application code, a counter-C++-philosopy thing. – Ethouris Jan 20 '15 at 18:16
11

clear() only clears the error flags. This is a common mistake. You want to call str(), and pass it an empty string to clear the buffer:

stream.str("");

will do what you want.

Max Lybbert
  • 19,717
  • 4
  • 46
  • 69