C++ 如何清除字符串流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2848087/
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
How to clear stringstream?
提问by There is nothing we can do
stringstream parser;
parser << 5;
short top = 0;
parser >> top;
parser.str(""); //HERE I'M RESETTING parser
parser << 6; //DOESN'T PUT 6 INTO parser
short bottom = 0;
parser >> bottom;
Why doesn't it work?
为什么不起作用?
回答by CB Bailey
Typically to 'reset' a stringstream you need to both reset the underlying sequence to an empty string with str
and to clear any fail and eof flags with clear
.
通常要“重置”字符串流,您需要使用 将底层序列重置为空字符串,str
并使用 清除任何失败和 eof 标志clear
。
parser.str( std::string() );
parser.clear();
Typically what happens is that the first >>
reaches the end of the string and sets the eof bit, although it successfully parses the first short. Operations on the stream after this immediately fail because the stream's eof bit is still set.
通常发生的情况是第一个>>
到达字符串的末尾并设置 eof 位,尽管它成功地解析了第一个短。此后对流的操作立即失败,因为流的 eof 位仍然设置。