环境:OS 10.7 + Xcode 4.2

 

想法:用scanf()的返回检测输入数据的合法性,同时清空键盘缓冲区以免错误的输入数据影响下次输入。

 

代码如下:

 1 #include<stdio.h>
 2 
 3 int bigger(int x, int y);
 4 int bigger(int x, int y)
 5 {
 6     if (x > y)
 7         return x;
 8     else return y;
 9 }
10 
11 int main(void)
12 {
13     int a, b, c;
14     int max, mark = 1;
15     int check;
16     
17     while (mark)
18     {
19         printf("Please enter three numbers(all zero to end): ");
20         //check validity of the input data
21         check = scanf("%d %d %d", &a, &b, &c);      
22         setbuf(stdin, NULL);     //rewind(stdin);         
23         if (check != 3)
24         { 
25             printf("Input Error!\n");
26             continue;  
27         }
28         //terminal condition
29         if (a == 0 && b == 0 && c == 0) 
30         {
31             mark = 0;
32             continue;
33         }
34                 
35         max = bigger(a, bigger(b, c));
36         printf("The biggest numbers is %d\n", max);
37     }
38     
39     printf("Thank you! ByeBye!\n");
40     return 0;
41 }

 

状况:

Please enter three numbers(all zero to end): a b c
Input Error!
Please enter three numbers(all zero to end): a a a
Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end): a 3 a
Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end):

 

分析、小结:

(1)scanf()遇到错误输入就返回,没有读入的数据继续存留在键盘缓冲区。

(2)在网上找了三个函数用来清空键盘缓冲区:

fflush(stdin);       遇到a a a的输入就进入死循环,其他没试。。。

rewind(stdin);      无异常。。。

setbuf(stdin, NULL);    状况如上。。而且这个函数也并非清空键盘缓冲区,暂时没弄明白作用,还需努力。。  

 

posted on 2012-11-01 13:44  youngsing  阅读(581)  评论(0编辑  收藏  举报