c++怎么读取文件行数

   2025-02-15 2370
核心提示:在C++中,可以使用以下方法读取文件的行数:#include iostream#include fstream#include stringint main() {std::ifstream file(

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

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言