lundi 26 avril 2021

While loop still prints once after EOF in C

I have to look through a file and take out the information of a student. It all works fine so far, there are 21 lines in the file, the first 20 contain information of a student and the final line contains just a single name. For some reason my while loop continues, sees that there's no information after that last line and stops but it still prints out that last line of the file with other lines of information in the in the output as well.

    count = 0;
    
    while(fscanf(fp, "%d", &average)!= EOF )
    {
        

        if(fscanf(fp, "%d", &average)!= EOF ){
            printf("\n/////////////////////////////////////////////////////////////////////////////");
            
            fscanf(fp, "%s", name);
            fscanf(fp, "%s", initial);
            fscanf(fp, "%s", surname);
            
            printf("\n\n\tName: %s \tInitial: %s \tSurname: %s\n", name, initial, surname);
            
            fscanf(fp, "%d", &year);
            fscanf(fp, "%s", coursename);
            fscanf(fp, "%s", group);
            fscanf(fp, "%d", &average);
            
            printf("\n\tYear: %d \tCourse Name: %s \tGroup: %s \tAverage: %d\n", year, coursename, group, average );
            printf("\n\tThis is entry number %d\n", count+1);
            printf("\n/////////////////////////////////////////////////////////////////////////////");
            count++;
        }
        if(fscanf(fp, "%d", &average) == EOF ){
             printf("\n\nThank you for using the program\n\nAll of the student records are now displayed\n");
        }

    }

   

    fclose(fp);
    return 0;
}

If the second last line for instance was

Mike (M) Johnson 3 IT A 66

it would print that out perfectly fine but the final thing in the file the name "John" it would print out

John Johnson 3 IT A 66

I don't understand firstly why it wouldn't take Mike Johnson's initial and secondly when it shouldn't print that line to begin with? I've tried setting the if statements and while statement to take the name as the end of the file but I think when I use "%s" to find that at the begining it seems to skip everything to the next string in the file over by 1, so Mike's name would become (M), and so on.

Aucun commentaire:

Enregistrer un commentaire