-1

I have been searching online for a long time and there is no correct answer as far as I can find. Now the most common answer looks like below:

int main() { 
    int number_of_lines = 0;
    std::string line;
    std::ifstream myfile("textexample.txt");

    while (std::getline(myfile, line))
        ++number_of_lines;
    std::cout << "Number of lines in text file: " << number_of_lines;
    return 0;
}

If the textexample.txt file actually has two empty lines at the end, this program will only count one of them, I'm guessing the first one. Such as below:

1
2
3

4
5
6


The above 6 numbers and 3 empty lines are 9 lines in total, but the program above will return 8.

I don't know why, but it seems std::getline() only loops 8 times.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Fluffy Skye
  • 101
  • 4

1 Answers1

1

The file in your example has 10 lines, of which 3 are empty. And if I run your code (with the missing includes...) it tells me there are 10 lines. So either you're running different code, or you're mis-quoting the file. Or you C++ standard library is broken somehow...

If I remove the line with "end", I get 9, not 8, lines.

einpoklum
  • 118,144
  • 57
  • 340
  • 684