0

I was trying to code a program which chooses a random number and ask to the user to guess it. When the user guesses it, the program asks to him if he wants to continue playing, typing 'y' for yes or 'n' for no. But it doesn't get my input and the program ends. Can someone help me to understand why? Thanks. Here's the script:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    srand(time(NULL));
    int guess;
    int number = 1 + rand() % 1000;
    char way = 'y';
    do
      {
      printf("I have a number between 1 and 1000.\n");
      printf("Can you guess my number?\n");
      printf("Please type your first guess.\n");
      scanf("%d", &guess);
      while (guess != number)
           {
           if (guess < number)
            puts("Too low. Try again!");
           else if (guess > number)
            puts("Too high. Try again!");
            scanf("%d", &guess);
            }
       printf("Excellent! You guessed the number!\n");
       printf("Would you like to play again (y or n)?: ");
       scanf("%c", &way);
       } while ('y' == way);
return 0;

}

Arthur
  • 1
  • 1
  • 2
    The lack of proper indentation makes it really difficult to make sense of your `while`s and `if`s. – Eugene Sh. Jul 14 '22 at 17:16
  • 3
    Simple solution: Change `scanf("%c", &way);`to `scanf(" %c", &way);` (note leading space in format string). – Some programmer dude Jul 14 '22 at 17:16
  • How can I check return value of scanf? Sorry for the indentation. – Arthur Jul 14 '22 at 17:20
  • @Arthur At the very least, say `if(scanf(…) != 1) { printf("input error!\n"); exit(1); }`. See also the [secret undocumented rules for avoiding stupid `scanf` problems](https://stackoverflow.com/questions/72178518#72178652). – Steve Summit Jul 14 '22 at 17:32

0 Answers0