简体   繁体   中英

Why doesn't fscanf convert set and then char?

If the file foobar.txt contains the text foobar , then in the following code

char s[16], c;
fp = fopen("foobar.txt", "r");
fscanf(fp, "%[f]s%c", s, &c);

fscanf returns 1 and not 2 as expected.

Whereas if I split the call to fscanf :

fscanf(fp, "%[f]s", s);
fscanf(fp, "%c", &c);

then both return 1 as expected.

Why doesn't the single fscanf work?

Because the s shouldn't be there, instead it should be

fscanf("%[f]%c", s, &c);

When scanf() finds the s in the format but not in the input it stops and returns 1 because up until then 1 argument matched.

The thing is, the s is not part of the format, the [] is the format specifier and it only contains a single character the f , so you should read the documentation more carefully and you can confirm that the s is not required for the format specifier, and in fact fscanf() is considering it as part of the requested input, but it's not there because after the f there is a o , try fsobar .

In the second case, it also stops and does not consume any character after the f and then the second call consumes a single character thus both return 1 correctly.

Just remove the s and modify it as follows.

fscanf("%[f]%c", s, &c);

In the first case, when fscanf() cannot find s in the input it stops and returns 1. In the second case, as you mentioned, its obvious that fscanf() will return 1.

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