“关闭一个错误”而在C ++中使用istringstream [英] "Off by one error" while using istringstream in C++

查看:208
本文介绍了“关闭一个错误”而在C ++中使用istringstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行以下代码时,我得到一个错误

I get an off by one error while executing the following code

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main (int argc, char* argv[]){
    string tokens,input;
    input = "how are you";
    istringstream iss (input , istringstream::in);
    while(iss){
        iss >> tokens;
        cout << tokens << endl;
    }
    return 0;

}

它打印出最后一个标记you两次,但是如果我进行以下更改一切正常。

It prints out the last token "you" twice, However if I make the following changes everything works fine.

 while(iss >> tokens){
    cout << tokens << endl;
}

任何人都可以解释while循环是如何工作的。感谢

Can anyone explain me how is the while loop operating. Thanks

推荐答案

这是正确的。条件 while(iss)仅在您读取超过流末尾后 才会失败。因此,从您的流中提取you之后,它仍然是真的。

That is correct. The condition while(iss) fails only after you read past the end of the stream. So, after you have extracted "you" from your stream, it will still be true.

while(iss) { // true, because the last extraction was successful

所以你尝试提取更多。此提取失败,但不会影响存储在 tokens 中的值,因此会重新打印。

So you try to extract more. This extraction fails, but does not affect the value stored in tokens, so it is printed again.

iss >> tokens; // end of stream, so this fails, but tokens sill contains
               // the value from the previous iteration of the loop
cout << tokens << endl; // previous value is printed again

出于这个原因,你应该总是使用第二种方法。在这种方法中,如果读取失败,则不会输入循环。

For this very reason, you should always use the second approach you show. In that approach, the loop will not be entered, if the read was unsuccessful.

这篇关于“关闭一个错误”而在C ++中使用istringstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆