How do you clear a stringstream variable?

后端 未结 8 1947
时光说笑
时光说笑 2020-11-22 13:53

I\'ve tried several things already,

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

both of which don\'t work.

相关标签:
8条回答
  • 2020-11-22 14:23
    m.str("");
    

    seems to work.

    0 讨论(0)
  • 2020-11-22 14:24

    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:

    m.str("");
    

    is correct, although using:

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

    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.

    0 讨论(0)
提交回复
热议问题