Is it possible for fscanf to return zero and consume input at the same time?

Is it possible to fscanfconsume input and return zero at the same time? For example, if I write

int res;
int k = fscanf(f, "%d", &res);

and check that k == 0, can I be sure that the next call fscanfin the same file fwill continue in the same place where the file was before the call fscanf?

+4
source share
3 answers

Another variation of the theme described in dasblinkenlight is:

for (int i = 0; i < 20; i++)
{
    int rc;
    int number;
    if ((rc = scanf(" this is the time for all good men (all %d of them)", &number)) == 0)
    {
        char remnant[4096];
        if (fgets(remnant, sizeof(remnant), stdin) == 0)
            printf("Puzzling β€” can't happen, but did!\n");
        else
        {
            printf("The input did not match what was expected.\n");
            printf("Stopped reading at: [%s]\n", remnant);
        }
    }
    else if (rc == 1)
        printf("%d: There are %d men!\n", i + 1, number);
    else
    {
        printf("Got EOF\n");
        break;
    }
}

Try in a file containing:

this is the time for all good men (all 3 of them)
this is the time for all good men (all 33 men)
   this   is   the
      time      for

all     good      men
(all

333 of

     them)
       this is the time for all good men to come to the aid of the party!

Etc.

Conclusion:

1: There are 3 men!
2: There are 33 men!
The input did not match what was expected.
Stopped reading at: [men)
]
4: There are 333 men!
The input did not match what was expected.
Stopped reading at: [to come to the aid of the party!
]
Got EOF

, , 'men)' ( "of them)" ). ( , %n) . , fgets() ( ), , . "this is the time for all good men" , "to come to the aid of the party" .

+3

, - %c, %[…] ( ) %n. , %d, , , , .

, :

int main(void) {
    int ignore; char c;
    int a = scanf("%d", &ignore);
    int b = scanf("%c", &c);
    printf("%d %d %c\n", a, b, c);
    return 0;
}

, scanf("%c", &c) (demo).

+3

, fscanf ?

"x"

scanf("%*d"); 
printf("%d\n", getchar());

ASCII- 'x', , getchar().

"-x". 45, ASCII- '-'.

,.... .... . 285) , , . (C11 Β§7.21.6.2 ΒΆ9)

285)fscanf . , strtod, strtol .., fscanf.

, 120 ('x'), "-" , 2 . . @Jonathan Leffler .

Thus, you can use a non-white space at the same time and return zero.


Space consumption is good here , and not empty space as part of a longer format.

+2
source

Source: https://habr.com/ru/post/1690876/


All Articles