【发布时间】:2014-12-22 08:21:03
【问题描述】:
问题如下:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float f = 0.0f;
int n = 0;
n = fscanf(stdin, "%f", &f);
printf("n = %d, f = %f\n", n, f);
return 0;
}
打印出来:
n = 1,f = 100.0000
如果输入字符串是:
100ergs
已提供给stdin。以下行为发生在 gcc (4.8.1) 和 VS2010(及更低版本)上。这是一个错误,还是我在这里遗漏了什么?因为第 7.19.6.2.19 和 7.19.6.2.20 节中的 c 标准 (c89) 明确指出,由于匹配失败,n 应该等于 0。
UPD。只是一些额外的信息:
1) 标准示例:
http://port70.net/~nsz/c/c99/n1256.html#7.19.6.2p20(感谢 Chris Culter 提供链接)
2) 匹配失败的类似示例,按预期工作:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int hex = 0x0;
int n = 0;
n = fscanf(stdin, "%x", &hex);
printf("n = %d, hexVal = %x\n", n, hex);
return 0;
}
如果 stdin 包含 0xz 输出是
n = 0, hexVal = 0
【问题讨论】:
-
不是匹配失败。遇到“e”时匹配停止,“ergs”未解析。如果你需要更细粒度的控制,可以考虑使用
strtod,这当然意味着你必须先从stdin读取一个字符串。 -
好的,但是上面部分中的标准确实明确指出,在那种确切的情况下(示例相对相同,输入相同)它是匹配失败。这就是让我感到困惑的地方......
-
@HighPredator,我不想将您的问题编辑得太远,但您可能想引用 C99 草案的 7.19.6.2.20 并链接到 port70.net/~nsz/c/c99/n1256.html#7.19.6.2p20 以供证明。
count = 0; // "100e" fails to match "%f"这行很重要。 -
@ChrisCulter,感谢链接。
-
没有问题,我是从stackoverflow.com/a/17015061 得到的 :)