[Solved] How do you clear a stringstream variable?

I’ve tried several things already,

std::stringstream m;

both of which don’t work.

Solution #1:

For all the standard library types the member function empty() is a query, not a command, i.e. it means “are you empty?” not “please throw away your contents”.

The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit (end-of-file), then calling clear() will set the error state back to goodbit (no error).

For clearing the contents of a stringstream, using:


is correct, although using:


is technically more efficient, because you avoid invoking the std::string constructor that takes const char*. But any compiler these days should be able to generate the same code in both cases – so I would just go with whatever is more readable.

Respondent: Wilka

Solution #2:

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

Respondent: Nikos Athanasiou

Solution #3:


seems to work.

Solution #4:

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

Respondent: jerron

Solution #5:

I am always scoping it:

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

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

    std::stringstream ss;
    ss << "heck";
Respondent: TimoK

Solution #6:

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


//fill up the streamstream variable
sstm << "crap" << "morecrap";
Respondent: Francisco Cortes

Solution #7:

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.

Solution #8:

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

    m.str() = "";

The following does empty the stringstream for me:

Respondent: John

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.