温馨提示×

c++怎么读取文件行数

c++
小亿
335
2023-11-10 23:56:31
栏目: 编程语言

在C++中,可以使用以下方法读取文件的行数:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("example.txt");
    
    if (!file) {
        std::cerr << "Failed to open the file." << std::endl;
        return 1;
    }
    
    int lineCount = 0;
    std::string line;
    
    while (std::getline(file, line)) {
        lineCount++;
    }
    
    std::cout << "The file has " << lineCount << " lines." << std::endl;
    
    file.close();
    
    return 0;
}

上述代码首先打开一个名为"example.txt"的文件,并检查是否成功打开。然后,使用std::getline函数逐行读取文件内容,每读取一行,行数加1。最后,输出文件的行数。

请确保在使用该代码时将文件名替换为你要读取的实际文件名。

0