C++流之间的区别是 false 和 eof()

C++ difference between stream is false and eof()

本文关键字:eof false 之间 区别 C++      更新时间:2023-10-16
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 34 5 67 8 97 8 9但是为什么要将while(stin)更改为while(!stin.eof())输出为

  • 1 2 34 5 67 8 9
那么while(stin)

和while(!stin.eof()有什么区别呢?多谢!

原因是在打印出变量之前,您没有检查读取是否成功。eof()检查会更早地停止读取(因为它到达std::istringstream末尾),但包含自己的微妙错误:

请参阅:为什么循环条件中的iostream::eof被认为是错误的?

例如,尝试在输入的末尾添加一个空格:"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;
    }
}