我想在C中扫描一个长类型后立即扫描一个字符。但是当我使用这个代码时它会失败。只有当我为字符定义一个单独的扫描功能时才能正确扫描。任何人都可以告诉我为什么会这样?
代码:
#include <stdio.h>
int main()
{
int a;
long b;
char c;
float d;
double e;
scanf("%d%ld%c", &a, &b, &c);
scanf("%f%lf", &d, &e);
printf("%d\n%ld", a, b);
printf("\n%c\n%.3f\n%.9lf", c, d, e);
return 0;
}
输入:
3 12345678912345 a 334.23 14049.30493
输出:
3
12345678912345
0.000
0.000000000
为什么会这样?
答案 0 :(得分:0)
c Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the char‐ acters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
3 12345678912345 a 334.23 14049.30493
^
代码中的%c与“12345678912345”后面的第一个空格字符匹配。这使得“a”与%f匹配。它不匹配,因此第二次scanf()调用失败(并且在没有匹配时返回0)。
RETURN VALUE
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in the
event of an early matching failure.
正如上面的评论所指出的,如果你在%c之前为格式字符串添加一个空格,你的问题就会消失 - 然后它将跳过空格并匹配'a'。然后指针将移过'a',第二个scanf将正常工作。
int number_matched;
number_matched = scanf("%d%ld %c", &a, &b, &c)