I have this text sample
Ahmed 10
kmal 5
doola 6
And I am using this code to read it
if (myfile.is_open())
{
while ( myfile.good() )
{
myfile >> name;
myfile >> phone;
cout << name <<" "<<phone<<endl;
}
myfile.close();
}
I get this output
Ahmed 10
kmal 5
doola 6
doola 6
Why does this code read the last line twice ?
Try
I believe the problem with the other approach is that eof isn’t signaled until you actually try to read more than you should. That is, when you attempt to
myfile >> nameon the last round. That fails, as doesmyfile >> phoneand only then do you break out of the loop.