C++ 获取总文件行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19140148/
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-27 22:32:49  来源:igfitidea点击:

C++ Get Total File Line Number

c++getnumberssizeline

提问by NewFile

Is there a function I can use to get total file line number in C++, or does it have to be manually done by forloop?

是否有一个函数可以用来获取 . 中的总文件行号C++,还是必须通过for循环手动完成?

#include <iostream>
#include <ifstream>

ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?

}

text.txt

文本文件

line1
line2
line3

回答by P0W

I'd do like this :

我会这样做:

   ifstream aFile ("text.txt");   
   std::size_t lines_count =0;
   std::string line;
   while (std::getline(aFile , line))
        ++lines_count;

Or simply,

或者简单地说,

  #include<algorithm>
  #include<iterator>
  //...
  lines_count=std::count(std::istreambuf_iterator<char>(aFile), 
             std::istreambuf_iterator<char>(), '\n');

回答by Olaf Dietsche

There is no such function. Counting can be done by reading whole lines

没有这样的功能。计数可以通过阅读整行来完成

std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
    ;

A note about scope, variable imust be outside for, if you want to access it after the loop.

如果要在循环后访问它,请注意范围,变量i必须在外for



You may also read character-wise and check for linefeeds

您还可以按字符阅读并检查换行符

std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
    if (c == '\n')
        ++i;

回答by duDE

I fear you need to write it by yourself like this:

我担心你需要像这样自己写:

int number_of_lines = 0;
 std::string line;
 while (std::getline(myfile, line))
        ++number_of_lines;

 std::cout << "Number of lines in text file: " << number_of_lines;

回答by Some programmer dude

Have a counter, initialized to zero. Read the lines, one by one, while increasing the counter (the actual contents of the line is not interesting and can be discarded). When done, and there was no error, the counter is the number of lines.

有一个计数器,初始化为零。逐行读取行,同时增加计数器(行的实际内容并不有趣,可以丢弃)。完成后,没有错误,计数器就是行数。

Or you can read all of the file into memory, and count the newlines in the big blob of text "data".

或者您可以将所有文件读入内存,并计算文本“数据”大块中的换行符。

回答by Yash

Fast way then above solutions like P0W one save 3-4 seconds per 100mb

快速方法然后像 P0W 这样的解决方案每 100mb 节省 3-4 秒

std::ifstream myfile("example.txt");

// new lines will be skipped unless we stop it from happening:    
myfile.unsetf(std::ios_base::skipws);

// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
    std::istream_iterator<char>(myfile),
    std::istream_iterator<char>(), 
    '\n');

std::cout << "Lines: " << line_count << "\n";
return 0;