Cómo contar las líneas de un archivo en C++?


¿Cómo puedo contar líneas usando las clases estándar, fstream y ifstream?

Author: Tshepang, 2010-06-19

7 answers

Qué tal esto: -

  std::ifstream inFile("file"); 
  std::count(std::istreambuf_iterator<char>(inFile), 
             std::istreambuf_iterator<char>(), '\n');
 89
Author: Abhay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-18 20:26:55

Usted lee el archivo línea por línea. Cuenta el número de líneas que lees.

 11
Author: Martin York,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-18 20:21:24

Esta es la versión correcta de la respuesta de Craig W. Wright:

int numLines = 0;
ifstream in("file.txt");
std::string unused;
while ( std::getline(in, unused) )
   ++numLines;
 9
Author: Billy ONeal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-08 21:25:01

Métodos del núcleo siguiendo @Abhay

Un código completo que he hecho:

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

No cambiará el estado de flujo del archivo de origen e incluye '\n'-procesamiento de la situación de miss para la última línea.

 0
Author: 小文件,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 07:53:17
int aNumOfLines = 0;
ifstream aInputFile(iFileName); 

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

return aNumOfLines;
 -1
Author: Maria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-14 14:34:12

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

Hay una cuestión de cómo tratar la última línea del archivo si no termina con una nueva línea. Dependiendo de lo que estés haciendo es posible que quieras contarlo y es posible que no. Este código lo cuenta.

Véase: http://www.cplusplus.com/reference/string/getline /

 -2
Author: Craig Wright,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-18 20:41:13

Divida el tamaño del archivo por el número medio de caracteres por línea!

 -10
Author: John,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-18 21:54:14