0

I'm pretty new to C and I'm trying to write a program that will guess a number that the player is thinking between 1 and 100. I think I've got it pretty much down. It can guess the number just fine. The only problem is that when it finishes guessing the number, it's supposed to ask whether or not the player wants to play again. I've got it running a while loop on the whole guessing process with a control variable going. For some reason, it's not waiting for user input when it asks whether or not to play again, but I'm using scanf("%c", result) just like I did for the other input I was receiving, but it doesn't work on this specific section. Any ideas why?

Here's the 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");
    }
  }
}

And here's a sample output of the program:

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>
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Andrew Graber
  • 177
  • 4
  • 12
  • 3
    In the loop the `getchar()` removed the extra newline characters on each pass, but you don't have this before the last `scanf()`. Better to use `scanf(" %c", &result);` to skip over initial whitespace. – ad absurdum Jan 09 '17 at 23:00
  • 2
    When coding you should **never trust the user** ! I have just tested your program by typing always `y` and the output was `101`. – Meninx - メネンックス Jan 09 '17 at 23:08

0 Answers0