c++でファイルの行数を取得する方法

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関数を使ってファイルの中身を一行ずつ読み込んで、一行読み込むごとにカウントを増やします。最後に、ファイルの行数を出力します。

お使いになる際は、ファイル名を実際に読み取るファイル名に置き換えてください。

bannerAds