C++简单文件读取

Thu*_*ura 1 c++

我有一个名为f1.txt的文件,其内容为75 15 85 35 60 50 45 70

这是我读取每个整数并打印它们的代码.

#include <iostream>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
  fstream file("f1.txt", ios::in);
  int i;
  while(!file.eof()) {
    file >> i;
    cout << i << " ";
 }

return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译并运行程序时,输出是75 15 85 35 60 50 45 70 70.为什么它读取最后一个整数两次?有线索吗?

dir*_*tly 6

尝试:

while(file >> i)
    cout << i << " ";
Run Code Online (Sandbox Code Playgroud)