By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,035 Members | 1,555 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,035 IT Pros & Developers. It's quick & easy.

Inputting From an External File and Testing for End of File

P: 14
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
Nov 5 '07 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
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.
Nov 5 '07 #2

P: 14
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.
Nov 5 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.