循环过来两次

时间:2013-10-27 21:19:58

标签: c

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

#include<stdio.h>

int main()
{
    char x ;

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

2 个答案:

答案 0 :(得分:1)

更改此行

scanf("%c",&x);

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

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

答案 1 :(得分:1)

%c说明符之前使用空格。在按 Enter 之后,这将有助于占用换行符\n,后续scanf读取。

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

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