C 一个程序说说scanf()判断
一道实例引起了关于
scanf()
的一点特性的思考:
1#include <stdio.h>
2
3int main(void)
4{
5 long num;
6 long sum = 0L;
7 int status;
8
9 printf("Please enter an integer to be summed. ");
10 printf("(q to quit): ");
11 status = scanf("%ld", &num);
12 while (status == 1)
13 {
14 sum = sum + num;
15 printf("Please enter next integer (q to quit):");
16 status = scanf("%ld", &num);
17 }
18 printf("Those integers sum to %ld.\n", sum);
19 return 0;
20}
21
这里用到了:
1 status = scanf("%ld", &num);
2 while (status == 1)
3
很明显赋值是给num
的,那么status
拿来何用?看起来似乎如果输入字符与格式符号不符(不能用%ld
说明符读取),就会返回0,符合则返回1,这样就可以判断输入的是否是指定的格式了。
评论 (0)