-4

我的代码看起来像这样,我无法解决它。它必须是一次

#include<stdio.h>

int main()
{
    char x ;

    printf("enter.\n");
    scanf("%c",&x);
    while(x!='D' && x!='d')
    {
        printf("diomond.\n");
        scanf("%c",&x);
    }
}
4

2 回答 2

1

更改此行

scanf("%c",&x);

scanf(" %c",&x); /* Notice the space in the format specifier */

运行两次的原因是当您输入一个字符时,输入流中会留下一个换行符,该换行符会在下一次迭代中使用。在格式字符串中使用前导空格将告诉 scanf() 忽略空格。

于 2013-10-27T21:25:21.233 回答
1

在说明符之前使用一个空格%c。这将有助于在按下 后吃掉\n留待下次阅读的换行符。 scanfEnter

scanf(" %c",&x);  
  //   ^space

while(x!= 'D'&& x!='d')
{
   printf("diomond.\n");
   scanf(" %c",&x);
     //   ^space
}
于 2013-10-27T21:25:46.520 回答