简体   繁体   中英

Read a text file using fscanf() in a while loop

So I am trying to read pairs of numbers from the input text file using fscanf() in a while loop. The text file would be something like the following:

(2, 50) (4, 30) (9, 30) (10, 400) (-5, -40)
(7, 20) (19, 200) (20, 50) (-18, -200) (-2, 29)

And my code is:

int main()
{
    FILE *fp;
    fp = fopen("File", "r");
    if (fp == NULL)
    {
        perror("Invalid input!");
        return 0;
    }
    else
    {
        int key, value;
        int check;
        while (fscanf(fp, "(%d,%d)", &key, &value) != EOF)
        {
            printf("(%d, %d)\n", key, value);
            check = fscanf(fp, "(%d,%d)", &key, &value);
            printf("%d", check);
        }
    }
    return 0;
}

But the output is instead of going through each pair in the file, it keeps printing (2,50) infinitely. Could someone help me to fix my code?

I was also hoping 'check' returns 2 at least since it has successfully two values which are 2 and 50. But it always return 0.

You have to read the space afterwards, this can be either done by:

fscanf(fp, "(%d,%d)%*c", &key, &value) . Here the %*c is reading one character and throwing it away.

or by

fscanf(fp, "(%d,%d) ", &key, &value) . Here you explicitly read the space.

Note:

I'm not sure why you are only printing the check afterwards, you are effectively skipping a pair, watch out for that.

Allow for white-space in the input

"(%d,%d)" does not read the space in between the parens: ) ( . Allow white-space before the '(' , ')' , ',' . "%d" already allows leading white-space.

// while (fscanf(fp, "(%d,%d)", &key, &value) != EOF)
while (fscanf(fp, " (%d ,%d )", &key, &value) != EOF)
//                 ^   ^   ^ 

Compare against the goal, not one of the failed goals

fscanf(fp, " (%d,%d )"... returns 2,1,0,EOF. Only when return value is 2 should the loop continue. With != EOF , loop continues when the return value is 2,1 or 0.

// while (fscanf(fp, " (%d ,%d )", &key, &value) != EOF)
while (fscanf(fp, " (%d ,%d )", &key, &value) == 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM