Link to home
Start Free TrialLog in
Avatar of derekpapesch
derekpapesch

asked on

Handling errors in getline

I am able to load a file just fine with the following:

    char HoldLineData[300];
    ifstream fin(LOAD_FILENAME);

    while (!fin.eof()) {
        fin.getline(HoldLineData,300);
            // Process line here
        }
    }

However, if the streamsize is greater than 300 in one particular line, naturally getline will fail, and nasty things happen to the processing of the line.  So, I check for a failure as follow:

    char HoldLineData[300];
    ifstream fin(LOAD_FILENAME);

    while (!fin.eof()) {
        fin.getline(HoldLineData,300);
            if (fin.fail()) {
                fin.clear();
            } else {
                // Process line here
            }
        }
    }

This code runs fine, providing there is data in the final line of the program.  However, if the final line of the file is is empty, eof is not reached and my program crashes.  

Should I be using a different method of extracting data, or have I made an error in my code?
ASKER CERTIFIED SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of derekpapesch
derekpapesch

ASKER

Ahhh!  That is so logical, It didn't occur to me that eof was also cleared by my clear().  

You're right, it is a infinite loop, I was crashing out of the ap.  

Thanks a million!