Connecting Tech Pros Worldwide Help | Site Map

Inputting From an External File and Testing for End of File

Newbie
 
Join Date: Sep 2007
Location: Gainesville
Posts: 14
#1: Nov 5 '07
Hello,
Several Weeks ago I asked a question about testing for the end of an input file.
I have been using this method pretty well for inputting information from an external file. I am using C++.
Expand|Select|Wrap|Line Numbers
  1. char line[50];
  2. while(file>>line){
Where line is a c-string and file is an input stream. But this only reads until the first space it encounters. I now want to try to take in an entire line, regardless of what it contains (such as whitespace) as a string and then parse the string later as appropriate.
When I try
Expand|Select|Wrap|Line Numbers
  1.  string line;
  2. while(getline(file, line)){ 
Is working fine until my input file ( .txt) has 2 or more white lines at the end or if I have a white line in the middle of the file.
If there is 0 or 1 white line at the end, I have no problems; however when I have 2 or more empty lines I run into trouble and my program crashes.

Could you please explain what is going wrong? What am I missing?

Thanks You
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#2: Nov 5 '07

re: Inputting From an External File and Testing for End of File


If getline() extracts no elements it sets the fail bit. Once the failbit is set all further calls to that istream fail since the fail bit is the first thing that getline() checks.

Probably you need to check that the rdstate is true and the eofbit is false. The rdstate will be false if the fail bit ti set. There is an isteream::eof() function that checks this. This function returns false if rdstate is true and eofbit is false. All other combonations return true.

If the rdstate is false and the eofbit is false, then you can clear the failbit and make rdstate true by calling the istream::clear() method.
Newbie
 
Join Date: Sep 2007
Location: Gainesville
Posts: 14
#3: Nov 5 '07

re: Inputting From an External File and Testing for End of File


Thanks,
I figured out what was causing the problem. The
Expand|Select|Wrap|Line Numbers
  1. while(getline(file,line)){
wasn't the problem. What was causing the program to crash was inside the while loop. I didn't realize that getline will actually return a string with nothing in it for an empty line. As I was parsing the data, if there was a white space, the string length was (previously not so obvious to me) 0. I had a couple of functions that assumed that the string length was automatically greater than 0. So I included a
Expand|Select|Wrap|Line Numbers
  1. if(line.length){
and this resolved the problem. I can now have as many white lines as I want where ever I want.
Reply


Similar C / C++ bytes