如何清除ostringstream [英] How to clear ostringstream
问题描述
ostringstream s;
s << "123";
cout << s.str().c_str() << endl;
// how to clear ostringstream here?
s << "456";
cout << s.str().c_str() << endl;
输出为:
123
123456
我需要:
123
456
如何重置ostringstream以获取所需的输出?
How can I reset ostringstream to get desired output?
推荐答案
s.str("");
s.clear();
第一行需要将字符串重置为空;第二行需要清除可能设置的任何错误标志。如果你知道没有设置错误标志或你不在乎重置它们,那么你不需要调用 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()
.
通常,使用一个新的 std :: ostringstream
对象而不是重用一个更简单,更简洁,更简单现有的,除非代码在已知的性能热点使用。
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.
这篇关于如何清除ostringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!