c++怎么讀取文件行數(shù)

c++
小億
590
2023-11-10 23:56:31

在C++中,可以使用以下方法讀取文件的行數(shù):

#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;
}

上述代碼首先打開(kāi)一個(gè)名為"example.txt"的文件,并檢查是否成功打開(kāi)。然后,使用std::getline函數(shù)逐行讀取文件內(nèi)容,每讀取一行,行數(shù)加1。最后,輸出文件的行數(shù)。

請(qǐng)確保在使用該代碼時(shí)將文件名替換為你要讀取的實(shí)際文件名。

0