是否有可能fscanf
消耗输入并同时返回零?例如,如果我写
int res;
int k = fscanf(f, "%d", &res);
并检查一下k == 0
,我可以确定下一次调用fscanf
在同一个文件上f
将在调用之前文件所在的同一位置继续fscanf
?
中概述的主题的另一个变体达斯布林肯灯's answer 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;
}
}
在包含以下内容的文件上尝试:
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.
Output:
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
' 不匹配。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)