Hi
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;
        exit(1);
    }
    newfile << 54 << endl;
    newfile << 12 << endl;
    newfile << 45 << endl;
    newfile.close();
    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;
        exit(1);
    }
    while(!openfile.eof()){
        openfile >> number;
        cout << number << endl;
    }
    openfile.close();

    system("PAUSE");
    return 0;
}

Recommended Answers

All 2 Replies

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

Thanks it worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.