Avatar ·

为什么在 C++ 中使用 `while (!stream.eof())` 是一个错误?

大家好!我是一名 C++ 初学者,在读取文件时遇到了问题。我写了一段代码,应该从文本文件中读取数字并显示在屏幕上: ```cpp #include #include #include int main() { std::ifstream file("numbers.txt"); std::vector numbers; int value; while (!file.eof()) { file >> value; numbers.push_back(value); } for (int n : numbers) { std::cout << n << " "; } return 0; } ``` 文件 `numbers.txt` 包含:`10 20 30 40`。我期望程序输出 `10 20 30 40`,但实际输出却是 `10 20 30 40 40`。也就是说最后一个数字被重复了。我尝试了不同的文件,问题依然存在——总是多添加最后一个元素的副本。为什么会这样?我明明在读取前检查了文件结尾。难道是我对 `eof()` 的理解有误?或者是编译器有 bug?请解释一下我哪里做错了。