scanf返回换行符

时间:2017-01-09 22:55:38

标签: c

我对C很陌生,我正在尝试编写一个程序来猜测玩家在1到100之间的数字。我想我已经把它弄得很糟糕了。它可以猜出这个数字就好了。唯一的问题是,当它完成猜测数字时,它应该询问玩家是否想再次玩。我已经在整个猜测过程中使用控制变量going运行了一个while循环。出于某种原因,当它询问是否再次播放时,它不是在等待用户输入,而是我正在使用scanf("%c", result),就像我为我接收的其他输入所做的那样,但它不能用于此具体部分。有什么想法吗?

这是source

#include <stdio.h>
#include <stdlib.h>
//

int
main(int argc, char **argv) {
  printf("Welcome to the High Low game...\n");

  // Write your implementation here...

  int going = 1;
  while(going)
  {
    printf("Think of a number between 1 and 100 and press <enter>\n");
    int low = 1, high = 100;
    char result;
    while(high >= low)
    {
      getchar();
      int mid = (low+high)/2;
      printf("Is it higher than %d? (y/n)\n", mid);
      scanf("%c", &result);
      if(result == 'y')
      {
        low = mid+1;
      }
      else if(result == 'n')
      {
        high = mid-1;
      }
      else
      {
        printf("BEEP! BOOP! INPUT NOT RECOGNIZED!!!\n");
        exit(0);
      }
    }
    printf("\n>>>>>> The number is %d\n\n", high+1);
    printf("Do you want to continue playing (y/n)?");
    scanf("%c", &result);
    printf("%c\n", result);
    if(result == 'n')
    {
      going = 0;
      printf("Thanks for playing!!!\n");
    }
  }
}

以下是该程序的output示例:

Welcome to the High Low game...
Think of a number between 1 and 100 and press <enter>

Is it higher than 50? (y/n)
y
Is it higher than 75? (y/n)
y
Is it higher than 88? (y/n)
n
Is it higher than 81? (y/n)
y
Is it higher than 84? (y/n)
n
Is it higher than 82? (y/n)
y
Is it higher than 83? (y/n)
y

>>>>>> The number is 84

Do you want to continue playing (y/n)?

Think of a number between 1 and 100 and press <enter>

0 个答案:

没有答案