lundi 23 avril 2018

How to count lines including the ending new lines?

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.text actually has two empty line 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


end

The above 6 numbers and 3 empty lines are 9 lines in total but the program above will return 8. Ignore the "end". I can't find other ways to put 2 new line after 6 when posting.

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

Aucun commentaire:

Enregistrer un commentaire