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,3 00);
// 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,3 00);
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?
char HoldLineData[300];
ifstream fin(LOAD_FILENAME);
while (!fin.eof()) {
fin.getline(HoldLineData,3
// 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,3
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
You're right, it is a infinite loop, I was crashing out of the ap.
Thanks a million!