开发者

How to clear ostringstream [duplicate]

开发者 https://www.devze.com 2023-02-16 07:03 出处:网络
This question already has answers here: How do you clear a stringstream variable? (9 answers) Closed 5 years ago.
This question already has answers here: How do you clear a stringstream variable? (9 answers) Closed 5 years ago.
ostringstream s;

s << "123";
cout << s.str().c_str() << endl开发者_运维问答;

// how to clear ostringstream here?
s << "456";
cout << s.str().c_str() << endl;

Output is:

123
123456

I need:

123
456

How can I reset ostringstream to get desired output?


s.str("");
s.clear();

The first line is required to reset the string to be empty; the second line is required to clear any error flags that may be set. If you know that no error flags are set or you don't care about resetting them, then you don't need to call clear().

Usually it is easier, cleaner, and more straightforward (straightforwarder?) just to use a new std::ostringstream object instead of reusing an existing one, unless the code is used in a known performance hot spot.

0

精彩评论

暂无评论...
验证码 换一张
取 消