C++ 简单文件读取

标签 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;
}

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

最佳答案

尝试:

while(file >> i)
    cout << i << " ";

关于C++ 简单文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586907/

相关文章:

c++ - 为什么局部函数定义在 C++ 中是非法的?

c++ - 递归 vector 模板

c++ - WRL : how to subscribe to events *without* using lambdas?

C++ 数据库连接?

c++ - 定义一个函数,使其可以接受列表或 vector

c++ - 访问传递给 new[] C++ 的数字

c++ - 使用 windows.h 的 Dev C++ 的简单线程示例

c++ - MS Visual Studio 到 Linux - 在 VirtualBox 中编译和调试

c++ - 我如何从 g++ 中获取缺少原型(prototype)的警告?

c++ - 未定义行为的意义何在?