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.