Jian Yu Loh
Jian Yu Loh

Reputation: 1

Looping fscanf causing additional loops (C language)

I am facing problems looping a fscanf. As in the code below (focus on the part where the while loop starts), I am looping the fscanf until it reached EOF. As you can see from the 2nd part below, the .txt file to fscanf from has only 6 strings,so the fscanf should only loop 6 times and then it reaches EOF. However, as you can see from the program output (2nd part belowe), the fscanf is looped 7 times. Since my program displays the missilenames in reverse order, I assume the while loop looped 1 additional time at the end, resulting at the blank line output on the first line of 3rd picture.

Can someone tell me how to fix this problem pls?

C CODE

while(fscanf(readmissiles,"\n %s \n",missilename)!=EOF)
        {
            missilename=malloc(20*sizeof(char));
            insertvalue(LL,missilename);
            missilenum++;
        }

TEXT FILE TO FSCANF FROM

single

splash

single

V-Line

h-line

Single

OUTPUT/DISPLAY

/there is a blank line displayed before the Single/

Single

h-line

V-Line

single

splash

single

7

Upvotes: 0

Views: 38

Answers (1)

KamilCuk
KamilCuk

Reputation: 141010

fscanf returns the number of elements scanned or EOF in case of error or end of file is reached before it could match anything. On the last loop fscanf returns 0 - it did not scan the element but it scanned \n, so it returns 0. Do:

while(fscanf(readmissiles, "%s", missilename) == 1)

Loop until there is one element scanned.

Upvotes: 0

Related Questions