I'm dealing with a problem using eof(). using
string name;
int number, n=0;
while(!in.eof())
{
in >> name >> number;
//part of code that puts into object array
n++;
}
sounds normal to me as it whenever there are no more text in the file. But what I get is n being 4200317. When I view the array entries, I see the first ones ats the ones in the file and other being 0s.
What could be the problem and how should I solve it? Maybe there's an alternative to this reading problem (having undefined number of lines)
This probably would be more correct
The eof is a bad practice.
Note that there is a subtle difference here from your code: your code ended when it encountered an
eof
or silently looped for infinite time if it found a wrong line (Hello World
for example), this code ends when it encounters a non correctly formatted "tuple" of name + number or the file ends (or there are other errors, like disconnecting the disk during the operation :-) ). If you want to check if the file was read correctly, after thewhile
you can check ifin.eof()
is true. If it's true, then all the file was read correctly.This looks like writing, not reading. Am I wrong?
You weren't initializing
n
, and you seem to have a typo.The correct way:
Why your code fails: