C++如何快速统计txt文件行数?

To quickly count the number of lines in a text file using C++, you can efficiently read through the file line by line and count each line until the end of the file is reached. Here's how you can achieve this:

cpp
#include <iostream> #include <fstream> #include <string> int countLinesInFile(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { std::cerr << "Error opening file: " << filename << std::endl; return -1; // Return -1 to indicate error } int lineCount = 0; std::string line; while (std::getline(file, line)) { lineCount++; } file.close(); return lineCount; } int main() { std::string filename = "example.txt"; // Replace with your file path int numLines = countLinesInFile(filename); if (numLines != -1) { std::cout << "Number of lines in file '" << filename << "': " << numLines << std::endl; } return 0; }

Summary:

To count lines in a text file efficiently using C++, you can open the file, read each line using std::getline, and count the lines until the end of the file. Ensure error handling for cases where the file cannot be opened. This method is straightforward and effective for small to moderately sized text files.

Keywords: C++, count lines in file, ifstream, getline, error handling