如何将字符串流的状态“重置”到创建它时的状态?
int firstValue = 1;
int secondValue = 2;
std::wstringstream ss;
ss << "Hello: " << firstValue;
std::wstring firstText(ss.str());
//print the value of firstText here
//How do I "reset" the stringstream here?
//I would like it behave as if I had created
// stringstream ss2 and used it below.
ss << "Bye: " << secondValue;
std::wstring secondText(ss.str());
//print the value of secondText here发布于 2011-10-02 07:40:43
这是我通常的做法:
ss.str("");
ss.clear(); // Clear state flags.发布于 2015-10-06 02:17:11
我会这么做的
std::wstringstream temp;
ss.swap(temp);编辑:修复christianparpart和Nemo上报的错误。谢谢。
PS:上面的代码在堆栈上创建一个新的stringstream对象,并将ss中的所有内容与新对象中的内容进行交换。
优势:
ss现在将处于一种全新的状态。ss内部数据重置为初始状态一样。更多信息:
std::move()不能保证移动的对象是空的。return std::move(m_container);不会清除m_container。所以你将不得不这样做auto to_return(std::move(m_container));m_container.clear();return to_return;
不可能比这更好
auto to_return;
m_container.swap(to_return);
return to_return;因为后者保证它不会复制缓冲区。
因此,只要适合我,我总是更喜欢swap()。
发布于 2018-02-18 05:19:26
根据上面的答案,我们还需要重置任何格式。总而言之,当构造新的std::stringstream实例时,我们将缓冲区内容、流状态标志和任何格式重置为它们的默认值。
void reset(std::stringstream& stream)
{
const static std::stringstream initial;
stream.str(std::string());
stream.clear();
stream.copyfmt(initial);
}https://stackoverflow.com/questions/7623650
复制相似问题