从字符串流输入值
是否有一个 while 循环允许我将字符串流的所有值输入到某种数据类型中?例如:
stringstream line;
while(/*there's still stuff in line*/)
{
string thing;
line >> thing;
//do stuff with thing
}
Is there a while loop that allows me to enter in all the values for a stringstream into some datatype? For example:
stringstream line;
while(/*there's still stuff in line*/)
{
string thing;
line >> thing;
//do stuff with thing
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是:
流操作(如
>>
)返回流;这就是允许您链接流操作的原因,例如:流可以用作布尔值;如果流处于良好状态(即,如果可以从中读取数据),则其计算结果为
true
;否则其计算结果为false
。这就是为什么我们可以使用流作为循环中的条件。流无法处于良好状态的原因有很多。
其中之一是当您到达流的末尾时(通过测试
line.eof()
来指示);显然,如果您尝试从流中读取所有数据,这就是您完成后期望流所处的条件。流不会处于良好状态的另外两个原因是如果出现某些内部错误或流上的操作失败(例如,如果您尝试提取整数但流中的下一个数据不代表整数) 。这两个都通过
line.fail()
进行测试。Yes:
Stream operations (like
>>
) return the stream; this is what allows you to chain stream operations, like:A stream can be used as a boolean; if the stream is in a good state (that is, if data can be read from it), it evaluates to
true
; otherwise it evaluates tofalse
. This is why we can use the stream as the condition in the loop.There are a number of reasons a stream will not be in a good state.
One of them is when you reach the end of the stream (indicated by testing
line.eof()
); obviously, if you're trying to read all the data out of the stream, this is the condition you expect the stream to be in when you are done.The other two reasons a stream will not be in a good state are if some internal error or if an operation on the stream failed (for example, if you try to extract an integer but the next data in the stream does not represent an integer). Both of these are tested by
line.fail()
.