c++怎么读取文件行数

c++
728
2023/12/6 23:56:31
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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。最后,输出文件的行数。

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++ list.sort的稳定性如何保证