/*
该程序用于测试,当输入为非数字时,scanf()函数的返回值
*/
#include <stdio.h>
int main(void) {
int num;
int a;
printf("Enter something:\n");
a = scanf("%d", &num);//a是scanf()的返回值,返回输入项的个数。
//如果输入的是一串字符,则a=0,num=0。
//因为输入转换说明符是"%d",说明该输入只接收整数,不接收字符或字符串。
printf("a=%d\n", a);
printf("num=%d\n", num);
return 0;
}
输入示例1:
当输入字符串“aaa”时,scanf()的返回值为0,num=0。
Enter something:
aaa
a=0
num=0
--------------------------------
Process exited after 3.981 seconds with return value 0
请按任意键继续. . .
输入示例2:
当输入数字155时,scanf()的返回值才为1。此时,num变量接受输入的数字155。
Enter something:
155
a=1
num=155
--------------------------------
Process exited after 5.013 seconds with return value 0
请按任意键继续. . .