如何读取动态大小的字符串流?
我想尝试使用 stringstream 来完成作业,但我对它的工作原理有点困惑。我进行了快速搜索,但找不到任何可以回答我的问题的内容。
假设我有一个具有动态大小的流,我如何知道何时停止写入变量?
string var = "2 ++ asdf 3 * c";
stringstream ss;
ss << var;
while(ss){
ss >> var;
cout << var << endl;
}
我的输出是:
2
++
asdf
3
*
c
c
我不确定为什么最后会得到额外的“c”,特别是因为 _M_in_cur = 0x1001000d7 ""
I wanted to experiment with stringstream for an assignment, but I'm a little confused on how it works. I did a quick search but couldn't find anything that would answer my question.
Say I have a stream with a dynamic size, how would I know when to stop writing to the variable?
string var = "2 ++ asdf 3 * c";
stringstream ss;
ss << var;
while(ss){
ss >> var;
cout << var << endl;
}
and my output would be:
2
++
asdf
3
*
c
c
I'm not sure why I get that extra 'c' at the end, especially since _M_in_cur = 0x1001000d7 ""
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最后您会得到额外的
c
,因为您没有测试执行提取后流是否仍然良好:您需要测试执行提取时和使用时之间的流状态结果。通常,这是通过在循环条件中执行提取来完成的:
You get the extra
c
at the end because you don't test whether the stream is still good after you perform the extraction:You need to test the stream state between when you perform the extraction and when you use the result. Typically this is done by performing the extraction in the loop condition:
代码中的
while(ss)
条件检查检查上次从流中读取是否成功。但是,即使您已读取字符串中的最后一个单词,此检查也会返回 true。只有ss>>的下一次提取代码中的 var
将使此条件为假,因为已经到达流的末尾&没有任何内容可以提取到变量 var 中。这就是你在最后得到一个额外的“c”的原因。您可以按照 James McNellis 的建议通过更改代码来消除此问题。The
while(ss)
condition check in your code checks if the last read from the stream was successful or not. However, this check is going to return true even when you have read the last word in your string. Only the next extraction ofss >> var
in your code is going to make this condition false since the end of the stream has been reached & there is nothing to extract into the variable var. This is the reason you get an extra 'c' at the end. You can eliminate this by changing your code as suggested by James McNellis.还有一个成员函数good(),它测试流是否可以用于I/O操作。所以使用这个上面的代码可以改为
There is also a member function good() which tests if the stream can be used for I/O operations. So using this the above code can be changed into