0

I have this readFile function.

void readFile(People peps[], int& cnt)
{
    ifstream in("people.txt");
    if (!in)
    {
        cout << "Error opening file\n";
    }
    else {
        while (in) //1
        while (!in.eof())//2
        {
            getline(in, peps[cnt].fullname, '-');
            getline(in, peps[cnt].h, '-');
            getline(in, peps[cnt].w, '\n');
            ++cnt;
        }
        in.close();
    }
} 

What is the difference between while(in) and while(!in.eof())? Before, I used while(!in.eof()) to detect the end of a file but then I saw my instructor use while (in) instead. I thought they were the same but it seems while(in) reads one more line even at the end of the file?

My people.txt file has 97 lines so cnt should be 97 after the while loop finishes executing. For some reason, when I use while(in), cnt ends up with 98, and peps[97] stores empty strings.

Starlight
  • 27
  • 1
  • 5
  • `!in` detects error conditions other than end of file. Either way, a `while (in)` or `while (!in.eof())` is not a good idea (effectively your code is assuming all the calls of `getline()` succeed, even if one or more of them fails, which means the count will be a bit whacky). – Peter Mar 24 '22 at 04:21
  • 1
    Don't use either: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – NathanOliver Mar 24 '22 at 04:29
  • `eof()` checks if the stream has *already* hit the end of the file. That is, it will only be set *after* an unsuccessful read. Related (but for C): [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/q/5431941/) – jamesdlin Mar 24 '22 at 04:31

2 Answers2

0

The while(in) condition includes all the reasons that make the file unreadable, not just eof.

I'm perplexed why that would result in an extra line. Maybe the last line of your file doesn't end with a newline character?

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Yes. The last line of my file is `Le Pham Ha Giang-162-49` so it does not contain a newline character. Does that mean I will have to have use while(!in.eof()) instead and cant customize the while(in)? – Starlight Mar 24 '22 at 04:20
  • @Starlight - That means your code will behave differently depending on whether the last line has a newline at the end or not. Usually not a good idea. – Peter Mar 24 '22 at 04:23
0

special function-> eof(), that returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream, and zero (meaning FALSE) otherwise.

Riyadh Ahmed
  • 121
  • 1
  • 6
  • Not quite true. `eof()` returns true *after* you've tried to read past the end of the file. The distinction is subtle but critical. – Mark Ransom Mar 24 '22 at 04:26