'Difference between while(in) and while(!in.eof())? [duplicate]
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.
Solution 1:[1]
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?
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark Ransom |
| Solution 2 | Riyadh Ahmed |
