i created a text file and put some numbers to it
but when i read from it, the last number will be printed out twice

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
    ofstream newfile("numbers.txt", ios::out);
    if (!newfile){
        cout << "File not found" << endl;
    newfile << 54 << endl;
    newfile << 12 << endl;
    newfile << 45 << endl;
    int number;
    string name;
    cout << "Enter name of a file: ";
    cin >> name;
    ifstream openfile(name.c_str(), ios::in);
    if (!openfile){
        cout << "File not found!" << endl;
        openfile >> number;
        cout << number << endl;

    return 0;

Don't use eof() as a loop control because it introduces a fencepost error. eof() returns true only after you try and fail to read from the stream. Instead, the >> operator will return a value that can be used as the condition without any operation ordering issues:

while (openfile >> number)
    cout << number << end;
This question has already been answered. Start a new discussion instead.