C++ 如何清除ostringstream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5288036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:49:32  来源:igfitidea点击:

How to clear ostringstream

c++stream

提问by Alex F

    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?

如何重置 ostringstream 以获得所需的输出?

回答by James McNellis

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().

第一行需要将字符串重置为空;第二行需要清除可能设置的任何错误标志。如果您知道没有设置错误标志或者您不关心重置它们,那么您不需要调用clear().

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

通常,使用新std::ostringstream对象而不是重用现有对象会更容易、更清晰、更直接(直截了当?),除非代码用于已知的性能热点。