[c++] How do you clear a stringstream variable?

I've tried several things already,

std::stringstream m;
m.empty();
m.clear();

both of which don't work.

This question is related to c++ stringstream

The answer is


This should be the most reliable way regardless of the compiler:

m=std::stringstream();

It's a conceptual problem.

Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.


You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state


I am always scoping it:

{
    std::stringstream ss;
    ss << "what";
}

{
    std::stringstream ss;
    ss << "the";
}

{
    std::stringstream ss;
    ss << "heck";
}

These do not discard the data in the stringstream in gnu c++

    m.str("");
    m.str() = "";
    m.str(std::string());

The following does empty the stringstream for me:

    m.str().clear();

m.str("");

seems to work.


my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";