为什么不能在 C 中将 scanf() 用于不同类型的多个输入参数?
Why can't you use scanf() in C for multiple input arguments of different types?
为什么这在 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=]
你需要写
// v---------v-----------v-- addresses taken here
scanf(" %d %c %f", &integer, &character, &floatingPoint);
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=]
你需要写
// v---------v-----------v-- addresses taken here
scanf(" %d %c %f", &integer, &character, &floatingPoint);
scanf
需要知道它应该写入它读取的值的位置,而不是当前驻留在那里的值。