如何在 C++ 中计算文件的行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3072795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:59:41  来源:igfitidea点击:

How to count lines of a file in C++?

c++file-ioiofstreamifstream

提问by malhobayyeb

How can I count lines using the standard classes, fstreamand ifstream?

如何使用标准类计算行数,fstream以及ifstream

回答by Abhay

How about this :-

这个怎么样 :-

  std::ifstream inFile("file"); 
  std::count(std::istreambuf_iterator<char>(inFile), 
             std::istreambuf_iterator<char>(), '\n');

回答by Martin York

You read the file line by line. Count the number of lines you read.

您逐行读取文件。计算你阅读的行数。

回答by Billy ONeal

This is the correct version of Craig W. Wright's answer:

这是 Craig W. Wright 回答的正确版本:

int numLines = 0;
ifstream in("file.txt");
std::string unused;
while ( std::getline(in, unused) )
   ++numLines;

回答by u4869018

kernel methods following @Abhay

@Abhay 之后的内核方法

A complete code I've done :

我完成的完整代码:

size_t count_line(istream &is)
{
    // skip when bad
    if( is.bad() ) return 0;  
    // save state
    std::istream::iostate state_backup = is.rdstate();
    // clear state
    is.clear();
    std::istream::streampos pos_backup = is.tellg();

    is.seekg(0);
    size_t line_cnt;
    size_t lf_cnt = std::count(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), '\n');
    line_cnt = lf_cnt;
    // if the file is not end with '\n' , then line_cnt should plus 1  
    is.unget();
    if( is.get() != '\n' ) { ++line_cnt ; } 

    // recover state
    is.clear() ; // previous reading may set eofbit
    is.seekg(pos_backup);
    is.setstate(state_backup);

    return line_cnt;
}

it will not change the origin file stream state and including '\n'-miss situation processing for the last line.

它不会改变原始文件流状态,并包括对最后一行的 '\n'-miss 情况处理。

回答by Maria

int aNumOfLines = 0;
ifstream aInputFile(iFileName); 

string aLineStr;
while (getline(aInputFile, aLineStr))
{
    if (!aLineStr.empty())
        aNumOfLines++;
}

return aNumOfLines;

回答by Craig Wright


int numLines = 0;
ifstream in("file.txt");
//while ( ! in.eof() )
while ( in.good() )
{
   std::string line;
   std::getline(in, line);
   ++numLines;
}

There is a question of how you treat the very last line of the file if it does not end with a newline. Depending upon what you're doing you might want to count it and you might not. This code counts it.

如果文件的最后一行不以换行符结尾,则存在一个问题。根据您在做什么,您可能想要计算它,也可能不会。这段代码算了。

See: http://www.cplusplus.com/reference/string/getline/

请参阅:http: //www.cplusplus.com/reference/string/getline/

回答by John

Divide the file size by the average number of characters per line!

将文件大小除以每行的平均字符数!