从一个小程序,再谈scanf的用法

下面这个程序:

 1 #include<stdio.h>
 2 int  main(void)
 3 {
 4        static int a[2][3]={{1,3,4},{7,9,6}};
 5        int i,j;
 6        while(1)
 7        {printf("Please input num:");
 8         
 9         //fflush(stdin);
10         scanf("i=%d,j=%d",&i,&j);
11         
12         if(i<2&&j<3)
13              printf("num=%d
",a[i][j]);
14         else printf("Input is error,
");
15        }
16         printf("programm is complete.
");
17     return 0;
18 }

当按要求,输入一个 ,比如 i=0,j=2 如下图

出现了死循环,原因这样的,

  像scanf("i=%d j=%d",&i,&j);这样的输入方式比较特别,vc6.0.显然在第一次输入后没有像正常情况一样清楚输入缓冲区,这样第二次执行scanf时,程序并没有让你输入而是直接读入上次输入的结果。如果你一定要这么做,应该在scanf之前加上:

    fflush(stdin);

  这样清楚掉键盘缓冲区。

下面这个程序

 1 #include<stdio.h>
 2 int  main(void)
 3 {
 4        static int a[2][3]={{1,3,4},{7,9,6}};
 5        int i,j;
 6        while(1)
 7        {printf("Please input num:");
 8         
 9         fflush(stdin);
10         scanf("i=%d,j=%d",&i,&j);
11         
12         if(i<2&&j<3)
13              printf("num=%d
",a[i][j]);
14         else printf("Input is error,
");
15        }
16         printf("programm is complete.
");
17     return 0;
18 }
原文地址:https://www.cnblogs.com/kalo1111/p/3281986.html