0

i got a problem over there. When i use the function below, i got a duplicate of the last entry in my agenda (array of records, "contact"s). How can i resolve this problem? Sorry if i asked a Q previously answered

void load(agenda a,int& r){
    r=0;
    contact c;
    fstream f;

    f.open("agenda.txt",ios::in);
    if(!f)
        cout<<"\nError!";
    else
        while(!f.eof()){
            f>>c.name;
            f>>c.number;
            strcpy(a[r].name,c.name);
            strcpy(a[r].number,c.number);
            r++;
        }
    f.close();
}
Cris
  • 13
  • 1

1 Answers1

0

The file need to reach EOF for eof() return true.

If there is a white space after the last value you won't reach the EOF till the next read try.

you can check if each read has succeeded like this:

if(!f>>value) break;

or iterate till >> operator will failed like this:

while(f>>c.name>>c.number){
   ...
}
SHR
  • 7,940
  • 9
  • 38
  • 57