为什么不能在C中使用scanf()来获取不同类型的多个输入参数?

时间:2015-01-15 22:49:43

标签: c scanf

为什么在C中这被认为是非法的?

#include <stdio.h>
int main()
{
    int integer;
    char character;
    float floatingPoint;

    scanf(" %d %c %f", integer, character, floatingPoint);

    return 0;
}

上面的代码在cc编译器下生成以下错误消息。

cc Chapter2ex1.c
Chapter2ex1.c: In function ‘main’:
Chapter2ex1.c:8:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type   ‘int’ [-Wformat=]
 scanf(" %d%c%f", integer, character, floatingPoint);
 ^
Chapter2ex1.c:8:5: warning: format ‘%c’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
Chapter2ex1.c:8:5: warning: format ‘%f’ expects argument of type ‘float *’, but argument 4 has type ‘double’ [-Wformat=]

1 个答案:

答案 0 :(得分:5)

你需要写

 //                 v---------v-----------v-- addresses taken here
 scanf(" %d %c %f", &integer, &character, &floatingPoint);

scanf需要知道它应该写入读取的值的位置,而不是当前驻留在那里的值。