while循环中scanf()函数被跳过的问题
在写一个循环输入时遇到的情况,在一个scanf()之后第二个scanf()被跳过;
于是写了段测试代码找找问题。
#include "stdio.h"
int main()
{
char s;
while(1)
{
printf("enter the value of s\n");
scanf("%c", &s);
printf("thr value of s is %c\n", s);
}
return 0;
}
上面这段代码的运行结果:
结果中s的值确实输出了,但是却连续输出了两次,看起来像是第二次的scanf()被忽略了,但为什么只是第二次的被忽略而第三次、第四次的没有?
回想一下在敲键盘时输入了一个’a’,结束时还输入了一个回车;
于是’a’和回车都进入了缓冲区;
而scanf("%c", &s);每次只读取一个字符,于是第一次读取到想要的输入’a’,而第二次读取到不该出现的空行;
要解决这个问题就是要把回车给去掉,可以采用以下方法:
1.利用getchar()从缓冲区读取回车,避免被下一次的scanf()读取到。(getchar()每次只读取一个字符)
2.利用fflush(stdin)将输入缓存清空,也可达到去除回车的目的。
#include "stdio.h"
int main()
{
char s;
while(1)
{
printf("enter the value of s\n");
scanf("%c", &s);
printf("thr value of s is %c\n", s);
getchar();
//fflush(stdin);//效果相同
}
return 0;
}
运行的结果:
问题解决。