1

I have created this function to return the number of lines in a text file:

int numberOfLinesInFile(string dataFile){            
    ifstream inputFile;
    inputFile.open("data.txt");
    int numberOfLines, data;

    while(!inputFile.eof()){
        inputFile >> data;
        numberOfLines++;
    }

    cout << "Number of lines: " << numberOfLines << endl;
    inputFile.close();
    return numberOfLines;
}

An interesting thing that I noticed is that the function counts the number of the non-blank lines (and an additional blank line at the end) correctly, but the additional blank lines are not being counted. For example, if this is my file:

234
453
657

then the function returns 4, since there are four lines in the text file. However, if my file contains more than one blank line at the end:

234
453
657



the function returns 4 again.

Why is this happening? Does this have to do with the eof instruction?


EDIT:

Okay, thank you @MikeCAT for making me understand where the problem was. Based on @MikeCAT's answer, I changed the while loop as:

while(!inputFile.eof()){
        if(inputFile >> data)
            numberOfLines++;
        else{
            cout << "Error while reading line " << numberOfLines + 1 << "!" << endl;
        }
}

I was incrementing numberOfLines without making sure that the line was actually read.

6cloud9
  • 162
  • 6
  • Related: https://stackoverflow.com/questions/5605125/ – Remy Lebeau Sep 26 '20 at 09:07
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case, that means changing `ifstream inputFile; inputFile.open("data.txt");` to `ifstream inputFile("data.txt");`. And you don't need to call `inputFile.close();`. The destructor will do that. – Pete Becker Sep 26 '20 at 12:41

1 Answers1

2

Firstly, you are doing numberOfLines++; after inputFile >> data; without checking if the reading is successful. This is bad and lead to an extra counting.

Secondly, inputFile >> data; reads integer and skip whitespace characters before integers.

To avoid these problems, you should use std::getline() to count lines.

Also don't forget to initialize numberOfLines.

int numberOfLinesInFile(string dataFile){            
    ifstream inputFile;
    inputFile.open("data.txt");
    int numberOfLines = 0;
    std::string data;

    while(std::getline(inputFile, data)){
        numberOfLines++;
    }

    cout << "Number of lines: " << numberOfLines << endl;
    inputFile.close();
    return numberOfLines;
}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58
  • Thank you @MikeCAT. I can now see where the problem was. – 6cloud9 Sep 26 '20 at 05:19
  • You could even take this a step further and use `std::cin.ignore()` instead of `cin::getline()` so that you are not wasting memory creating `std::string` values that are not used for anything. – Remy Lebeau Sep 26 '20 at 09:09