我有此代码:
char c;
do
{
scanf("%c",&c);
printf("coucou\n");
} while (c!='q');
这里是我的结果:
输入:
M
输出:
coucou
coucou
为什么每次都打印两次“ coucou”?
因为scanf
扫描2个字符,所以循环执行了2次,一个扫描M
,另一个扫描\n
新行字符。
您可以通过在循环中添加条件来轻松解决此问题:
do
{
if(getchar() != '\n')
printf("coucou\n");
} while (c!='q');