Bản hack của bạn làm giảm số đếm ở cuối là chính xác – một bản hack.
Tốt hơn hết là viết chính xác vòng lặp của bạn ở vị trí đầu tiên, vì vậy nó không tính dòng cuối cùng hai lần.
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;
}
Cá nhân, tôi nghĩ trong trường hợp này, mã kiểu C là hoàn toàn chấp nhận được:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
Chỉnh sửa: Tất nhiên, C++ cũng sẽ cho phép bạn làm một cái gì đó tương tự một chút:
int main() {
std::ifstream myfile("textexample.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
}