How do you clear a stringstream variable?


I've tried several things already,

std::stringstream m;

both of which don't work.

This question is tagged with c++ stringstream

~ Asked on 2008-08-21 18:35:57

8 Answers


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.

~ Answered on 2008-08-21 19:00:25


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

~ Answered on 2014-04-24 10:34:52



seems to work.

~ Answered on 2008-08-21 18:36:18


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


~ Answered on 2012-10-11 16:00:12


I am always scoping it:

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

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

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

~ Answered on 2014-03-26 17:37:19


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";

~ Answered on 2013-10-18 00:34:05


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.

~ Answered on 2014-10-10 20:04:50


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

    m.str() = "";

The following does empty the stringstream for me:


~ Answered on 2012-09-06 22:58:41

Most Viewed Questions: