ifstream 识别文件结尾

ifstream identifying end of file

我有一个包含以下格式数据的文件:

name1 p1 p2 ... p11
name2 p1 p2 ... p11
...

(参数不一定在一行)

我的目标是读取名称和 11 个参数,对它们做一些事情,然后对下一个数据块做同样的事情,直到没有更多。下面的代码做得很好,但在到达文件末尾后,它又做了一个 运行 读取垃圾。谁能帮我解决这个问题?

std::ifstream file("data.txt");
std::string name;
double p[11];

while(file.peek() != EOF){
    file >> name 
         >> p[0] >> p[1] >> p[2] >> p[3]
         >> p[4] >> p[5] >> p[6] >> p[7]
         >> p[8] >> p[9] >> p[10];
/* 
    doing something with the data
*/
}
file.close();

在 C++ 中执行此操作的常用方法是在提取后检查流状态:

while(file >> name 
           >> p[0] >> p[1] >> p[2] >> p[3]
           >> p[4] >> p[5] >> p[6] >> p[7]
           >> p[8] >> p[9] >> p[10]) {
/* 
    doing something with the data
*/
}

如果没有更多数据或输入错误,循环将停止。

这里有更多信息是如何以及为什么起作用的:

std::basic_ios::operator bool