Displaying the last piece of data twice

Hello Everyone,

I've been learning how to read and write to files in cpp. For a reason I cannot figure out, my last piece of data in the file is read twice. Is someone able to tell me why this is? I'm 100% positive that the piece of data is only in the file once.

Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    int numbers;
    string file;
    cout << "Enter a file name: ";
    getline(cin, file);
    ifstream readFile(file.c_str(), ios::in);
    while(!readFile.eof()) {
        readFile >> numbers;
        cout << numbers << endl;
    }
    readFile.close();
    return 0;
}
Last edited on
You have a blank line in your text file. One of the most common issues with file streaming.
Thanks, I was inputting data into the file using a loop and I have an endl; after the last piece of data. I guess I have to break the loop early before the last piece of data so I don't leave a blank at the end.

Thanks again!
Topic archived. No new replies allowed.