0

I have a file I read , and I want to start by counting the number of lines, so I did

I want to count the number of lines in a input file

void foo(ifstream &MyList) 
{
    int nb_lines = 0;
    string line;
    for (nb_lines; getline(MyList,line); nb_lines++) {};
    [...]
}

Which is I guess not the right way to do it, but it does the work. How should I have done ?

In addition, compiler tells me that statement has no effect, which is false (value of nb_lines is changed). Can I make him understand that? ---> just use for (; getline(MyList,line); nb_lines++) {};

sayanel
  • 301
  • 2
  • 12
  • The compiler yells at you about `nb_lines;`, not `nb_lines++;`. – Zeta Mar 14 '19 at 21:03
  • that right, I can just remove it thank – sayanel Mar 14 '19 at 21:06
  • [How to count lines of a file in C++?](https://stackoverflow.com/questions/3072795/how-to-count-lines-of-a-file-in-c) – sebastian Mar 14 '19 at 21:09
  • "---> just use for (; getline(MyList,line); nb_lines++) {};" if this is supposed to be an answer you should post it as answer but you should not include it in the question, if not, I dont understand what the question is about – 463035818_is_not_an_ai Mar 14 '19 at 21:23
  • sayanel, If the file was only 3 bytes `"abc"` with no trailing `'\n'`, would you count that a s 1 or 0 line file? – chux - Reinstate Monica Mar 14 '19 at 21:25
  • @sebastian the `std::count` approach is invalid and cannot handle a proper count where there is no POSIX `eof`. Using `getline` and a counter provides a proper count regardless. There are a number of common editors that do not write a POSIX `eof` (e.g. a `'\n'` after the final line) even today. The `std::count` approach fails to count the final line without a line-ending. – David C. Rankin Mar 14 '19 at 21:46

1 Answers1

1
void foo(ifstream &MyList) {
    int nb_lines = 0;
    string line;
    for (; getline(MyList,line); nb_lines++);
    // alternatively
    while( getline(MyList,line) )
        ++nb_lines;
}

Thats enought normally.

Dimfred
  • 182
  • 2
  • 16