流之间的C ++差异是假的和eof()

时间:2014-11-16 03:32:58

标签: c++

string tmp("f 1/2/3 4/5/6 7/8/9");
istringstream stin(tmp);
string token;
char ch;
int a,b,c,e;
stin >> token;
while(stin){
    stin >> a >> ch >> b >> ch  >>c;
    cout <<a <<  " "<<b <<" "<<c <<  endl;
}

为什么输出是 1 2 3 4 5 6 7 8 9 7 8 9 但是为什么要改变while(stin)到while(!stin.eof()) 输出是

  • 1 2 3 4 5 6 7 8 9

那么while(stin)和while(!stin.eof())之间有什么区别? 非常感谢!

1 个答案:

答案 0 :(得分:3)

原因是您在打印变量之前不检查读取是否成功。 eof()检查会提前停止读取(因为它会到达std::istringstream的末尾),但包含其自身的细微错误:

请参阅: Why is iostream::eof inside a loop condition considered wrong?

例如,尝试在输入的末尾添加一个空格:"f 1/2/3 4/5/6 7/8/9 ",然后通过eof()检查得到相同的重复输出。

理想的解决方案可能是这样的:

int main()
{
    istringstream stin("f 1/2/3 4/5/6 7/8/9");

    string token;

    char ch;
    int a, b, c;

    stin >> token;
    while(stin >> a >> ch >> b >> ch >> c) // only loop on successful read
    {
        cout << a << " " << b << " " << c << endl;
    }
}