C语言的循环语句中使用 scanf(“%c“,&x); 输入字符时的问题

【示例代码】 下面代码,是在C语言的循环语句中使用 scanf("%c",&x); 输入字符,但输出的结果出乎意料。 原因详见问题分析。

#include

#include

char ch;

int n;

int main() {

while(n<5) {

printf("Please enter a letter: ");

scanf("%c",&ch);

printf("%c\n",ch);

n++;

}

return 0;

}

【问题分析】 本例代码执行后,会输出如下错误结果:即多了一条“Please enter a letter:”的提示。

Please enter a letter: M

M

Please enter a letter:

Please enter a letter:

原因在于,在C语言中,利用 scanf("%c",&x); 输入一个字符后的回车,会被作为字符存入缓冲区。 因此,第一次调用 scanf("%c",&x); 输入一个字符后的回车,被作为字符存入缓冲区。当下一次调用 scanf("%c",&x); 时,会从缓冲区取出回车符作为输入,这就在输入逻辑上造成了混乱。所以,就输出了出乎意料的结果。【解决方法及正确代码】 将scanf("%c",&ch); 改为 scanf(" %c",&ch); 便可。即在%c前加一个空格。因为%c前面的空格,将清除缓冲区的内容。此外,getchar()函数也具有清除缓冲区的功能。所以,本例至少有两种解决方法。 方法一代码:

#include

#include

char ch;

int n;

int main() {

while(n<5) {

printf("Please enter a letter: ");

scanf(" %c",&ch); //clear buffer and enter a letter

printf("%c\n",ch);

n++;

}

return 0;

}

方法二代码:

#include

#include

char ch;

int n;

int main() {

while(n<5) {

printf("Please enter a letter: ");

scanf("%c",&ch);

printf("%c\n",ch);

getchar(); //clear buffer

n++;

}

return 0;

}

【参考文献】https://blog.csdn.net/weixin_43260673/article/details/111460487https://blog.csdn.net/qq_34316892/article/details/107459774