Do-while循环scanf读取循环两次,而不是读取单个字符时读取一次

问题描述 投票:0回答:1

我有此代码:

char c;
do
{
    scanf("%c",&c);
    printf("coucou\n");
} while (c!='q');

这里是我的结果:

输入:

M

输出:

coucou
coucou

为什么每次都打印两次“ coucou”?

c char scanf
1个回答
1
投票

因为scanf扫描2个字符,所以循环执行了2次,一个扫描M,另一个扫描\n新行字符。

您可以通过在循环中添加条件来轻松解决此问题:

do
{
  if(getchar() != '\n')  
    printf("coucou\n");
} while (c!='q'); 
© www.soinside.com 2019 - 2024. All rights reserved.