Avatar ·

Why is using `while (!stream.eof())` in C++ a mistake?

Hello everyone! I'm a beginner C++ developer, and I've encountered a problem with reading files. I wrote code that should read numbers from a text file and output them to the screen: ```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; } ``` The file `numbers.txt` contains: `10 20 30 40`. I expect the program to output `10 20 30 40`, but instead it outputs `10 20 30 40 40`. That is, the last number is duplicated. I tried different files, and the problem repeats — an extra copy is always added.