c语言清除缓冲区的数据?

#include <stdio.h>
main()
{
int a,b,max,ret;
printf("Input a,b:");
ret = scanf("%d,%d",&a,&b);
while (ret!=2)
{
while(getchar()!='n');
printf("Input a ,b:");
ret = scanf("%d,%d",&a,&b);
}
max =a >b? a:b;
printf("max = %d\n",max);
}
其中第二个while循环什么作用?
while(getchar()!='n');
printf("Input a ,b:");
ret = scanf("%d,%d",&a,&b);
怎么清除的缓冲区中的错误数据?
对不起打错了··第二个循环 ·while(getchar()!='\n');
是怎么回事?

while(getchar()!='n'); -- 应当是 while(getchar()!='\n'); 这是不断循环取字符,直到取到 Enter 键时结束循环。作用,清除上面一次输入时残留在输入流中的字符。
改用 fflush(stdin); 更佳。
ret = scanf("%d,%d",&a,&b); ret 为成功读得的数据个数。
清除的缓冲区中的残留数据: if (ret != 2) fflush(stdin);
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-04-01
要想实现a,b的输入,先要打个回车确认后再给A,B赋值
第2个回答  2013-03-31
while(getchar()!='n'); //空循环,仅当输入n时跳出。重新输入ab前需要敲一个'n'确认
输入缓冲区不需要清除。输出的不能清除追问

对不起打错了··第二个循环 ·while(getchar()!='\n');
是怎么回事?

追答

重新输入ab前需要敲一个'\n'(回车)确认

第3个回答  2013-04-01
仅当输入n时跳出。重新输入ab前需要敲一个'n'确认。。
第4个回答  2013-04-01
'\n'是回车,
while(getchar()!='\n')就是说, 输入的字符不是 回车 就进入循环
相似回答