C 文件线计数

C++ fileIO line count

本文关键字:文件      更新时间:2023-10-16
ifstream inFile;
inFile.open(filename); //open the input file
stringstream strStream;
strStream << inFile.rdbuf(); //read the file
string str = strStream.str(); //str holds the content of the file

我正在使用此代码从文件中读取。我需要在该文件中获取行数。有没有第二次阅读文件的方法可以做到这一点?

您已经有字符串中的内容,因此只需检查该字符串:

size_t count = 0, i = 0, length = str.length();
for(i=0;i<length;i++)
    if(str[i]=='n') count++;

我会很想这样做:

auto no_of_lines = std::count(str.begin(), str.end(), 'n');

std::countalgorithm库中帮助您。

#include <algorithm>
#include <iterator>
//...
long long lineCount { std::count(
        std::istreambuf_iterator<char>(inFile),
        std::istreambuf_iterator<char>(),
        'n') };
std::cout << "Lines: " << lineCount << std::endl;