Adam
Adam

Reputation: 39

Skipping lines in a file in c

I'm trying to read to contents of a file, insert them into the fields of a structure, and print out the values. But it seems to ignore half of the patient's data because it skips a line containing data every time.

Sophia Jackson 1234 141.0 1.1 

Emma Aiden 5432 142.0 1.2

Olivia Lucas 5685 143.0 1.3

Ava Liam 5672 144.0 1.4

Mia Noah 3467 145.0 1.5

Isabella Ethan 8654 146.0 1.6

Riley Mason 2567 147.0 1.7

Aria Caden 6794 148.0 1.8

The names are formatted like so, except they aren't newlines in between each one

while(1) {
        fscanf(fp,"%s %s %i %f %f",newptr->pfn,newptr->pln,&newptr->pid,&newptr->pwt,&newptr->phgnum);
        printf("First Name: %s\n",newptr->pfn);
        printf("Last Name: %s\n",newptr->pln);
        printf("PID: %i\n",newptr->pid);
        printf("Weight: %f\n",newptr->pwt);
        printf("HG1AC: %f\n",newptr->phgnum);

        if( 5 != fscanf(fp,"%s %s %i %f %f",newptr->pfn,newptr->pln,&newptr->pid,&newptr->pwt,&newptr->phgnum)) {
             break;
        }           
}

Upvotes: 0

Views: 1416

Answers (2)

David R Tribble
David R Tribble

Reputation: 12204

Your second call to fscanf() reads the second line of data, overwriting the data previously read from the first line by the first fscanf().

You need only one fscanf() within your loop.

Also, how are you setting/changing newptr within the loop?

Addendum (9 May 2018)

You should use only one fscanf() call within your loop. Furthermore, you should check the result of that call at the top of the loop to determine when you've hit EOF, and thus when to terminate the loop.

You could also call feof() to check for EOF before reading the next line.

Upvotes: 3

Sujith Gunawardhane
Sujith Gunawardhane

Reputation: 1311

There are 2 fscanf function calls within the while loop. You consider the first one for displaying and the results of the second call just ignored. That means you ignore half from all data.

Following will solve the issue.

while(1){

        if( 5 != fscanf(fp,"%s %s %i %f %f",newptr->pfn,newptr->pln,&newptr->pid,&newptr->pwt,&newptr->phgnum)){
             break;
        }           

        printf("First Name: %s\n",newptr->pfn);
        printf("Last Name: %s\n",newptr->pln);
        printf("PID: %i\n",newptr->pid);
        printf("Weight: %f\n",newptr->pwt);
        printf("HG1AC: %f\n",newptr->phgnum);
}

Upvotes: 2

Related Questions