简体   繁体   English

为什么fscanf不先转换set然后再转换char?

[英]Why doesn't fscanf convert set and then char?

If the file foobar.txt contains the text foobar , then in the following code 如果文件foobar.txt包含文本foobar ,则在以下代码中

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

fscanf returns 1 and not 2 as expected. fscanf返回1而不是2。

Whereas if I split the call to fscanf : 而如果我将调用拆分为fscanf

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

then both return 1 as expected. 然后两个都按预期返回1。

Why doesn't the single fscanf work? 为什么单个fscanf不起作用?

Because the s shouldn't be there, instead it should be 因为s不应该在那里,所以应该

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. scanf()以格式而不是输入形式找到s ,它将停止并返回1因为直到1个参数都匹配为止。

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 . 关键是, s不是格式的一部分, []是格式说明符,它仅包含单个字符f ,因此您应更仔细地阅读文档,并可以确认s不需要格式说明符,实际上fscanf()会将其视为请求的输入的一部分,但它不存在,因为f后面有一个o ,请尝试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. 在第二种情况下,它也停止并且不占用f之后的任何字符,然后第二次调用消耗单个字符,因此两者均正确返回1

Just remove the s and modify it as follows. 只需删除s并对其进行如下修改。

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. 在第一种情况下,当fscanf()在输入中找不到s时,它将停止并返回1。在第二种情况下,如您所述,很明显fscanf()将返回1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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