C++ 清空字符串流的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/834622/
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
Best way to empty stringstream?
提问by Brian R. Bondy
One of the possibilities is:
一种可能性是:
somestringstream.str("");
But is it most optimal? Is there any way to preserve stringstream internal buffer, so that following operator<<() calls would not require to reserve memory again?
但它是最优化的吗?有什么方法可以保留 stringstream 内部缓冲区,以便后面的 operator<<() 调用不需要再次保留内存?
回答by Brian R. Bondy
I've always done:
我一直这样做:
s.clear();//clear any bits set
s.str(std::string());
@litb gets into more detailabout how to seekp to the start of the stream combined with std::ends you can keep your allocated size.
@litb更详细地了解如何结合 std::ends 查找流的开头,您可以保持分配的大小。