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.