I m reading data from a text file and then printing it. I am not sure what I am doing wrong but the program prints the last line that it reads twice.

void bank_account::viewHistory()
{
    ifstream in_file("bank_transaction_history.txt" , ios::in);
    if(!in_file)
    {
        cout<<"File error \n";
    }
    cout<<"Event"<<setw(15)<<"Amount"<<setw(15)<<"Date"<<setw(20)<<"Current Balance"<<endl;
    string eve,dat;
    double am,bal;
    while(!in_file.eof())   
    {
        in_file>>eve>>am>>dat>>bal;   //reading data from file
        cout<<eve<<setw(10)<<am<<setw(20)<<dat<<setw(10)<<bal<<endl; 
    }

    in_file.close();
}

Recommended Answers

All 3 Replies

It's because you're using eof() incorrectly eof() doesn't know it's end-of-file until an attempt is made to read it. A better loop is like this. Note: eof() is unnecessary, at least I've never found a use for it.

while(in_file>>eve>>am>>dat>>bal )   
    {
        cout<<eve<<setw(10)<<am<<setw(20)<<dat<<setw(10)<<bal<<endl; 
    }

Thanks a lot!

Separating the check for end-of-file from the actual read is risky, and you're encountering a very common beginner's problem with it: the last line gets processed twice. This is because the eof member function won't tell you that the next input request will hit end-of-file, only whether the previous one did. Since you unconditionally process what was read (or not read in this case) after reading from the file, the last line gets processed twice.

Since the >> operator returns a reference to your stream and the stream object has a boolean conversion for the stream's state, you can do it right with less code:

while(in_file>>eve>>am>>dat>>bal)   
{
    cout<<eve<<setw(10)<<am<<setw(20)<<dat<<setw(10)<<bal<<endl; 
}
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.