-7

Hello I'm trying to write a simple number guessing game in c. If the player guesses the number correctly, the program will give a message and aks if the player want to play again.

When i compile the code, it generate the random number, let the player guess the number and check whether the number is right or not. But when it aks if the player want to play again, it does not let the player answer and instead just exit. I don not know why it happens. Can you please help me?

int main()
{ 

int number, guess_value,number_of_guesses;
char answer;

srand((unsigned)time(NULL));
number=rand() %100+1;

A:number_of_guesses=0;
while (guess_value != number){
    printf("\nEnter a number between 0 and 100\n");
    scanf("%d", &guess_value);      
    number_of_guesses++;
    if (guess_value == number){
        printf("Right !!! You win\n");
    }
    else if (guess_value > number){
        printf("\nYour guess is too high. Guess again");
    }
    else {printf("\nYour guess is too low. Guess again");
    }
}

printf("You guessed %d times !", number_of_guesses);

printf("Do you want to play again? y? n?");
scanf("%c", &answer);
if (answer == 'y'){ 
    goto A; /*return to to beginging*/
}
return 0;   
}
Minh
  • 61
  • 5
  • 1
    What does not work? Do you have an error message? – Michiel Pater Feb 17 '16 at 15:16
  • In order to get better responses I recommend providing better information. "Somehow it does not work" is not sufficient. It may not work because (1) It does not compile; (2) because while it compiles, it does not link; (3) while it compiles and links, it crashes; (4) while it compiles, links and doesn't crash, it fails to behave in the expected way. Each of the possible levels of failure produce output which is tremendously helpful in finding the reason for the failure. – Peter - Reinstate Monica Feb 17 '16 at 15:19
  • And for a more consistent style I suggest that a program which uses goto should perform *all* flow control with goto. Using a while loop in a program with goto is like having a digital watch in a Western movie. – Peter - Reinstate Monica Feb 17 '16 at 15:25
  • The question is poorly written and no explanation is given. – ITguy Feb 17 '16 at 15:28
  • Thank you for your comments. I'm new to this site and this is my first post. I have edited the question so that it is clearer to understand. I'l pay more attention the next time. – Minh Feb 17 '16 at 15:40
  • Since you are a beginner, I would recommend *not* using `goto` ever. Otherwise you'll use it like a crutch when you can't figure out the right loop logic. – Gillespie Feb 17 '16 at 16:39
  • @RPGillespie Thanks for your advice. I'll pay attention to that – Minh Feb 17 '16 at 17:11

6 Answers6

4

I think the problem is that you compare guess_value before initialization.

Daniele
  • 821
  • 7
  • 18
1

Corrected code is:

int main()
{
    int number, guess_value,number_of_guesses;
    char answer;

    srand((unsigned)time(NULL));

    do
    {
        number=rand() %100+1;
        number_of_guesses=0;
        do
        {
            printf("\nEnter a number between 0 and 100\n");
            scanf("%d", &guess_value);
            number_of_guesses++;
            if (guess_value == number)
            {
                printf("Right !!! You win\n");
            }
            else if (guess_value > number)
            {
                printf("\nYour guess is too high. Guess again");
            }
            else
            {
                printf("\nYour guess is too low. Guess again");
            }
        }
        while (guess_value != number);

        printf("You guessed %d times !\n", number_of_guesses);

        printf("Do you want to play again? y? n?");

        scanf(" %c", &answer);
    }
    while (answer == 'y');

    return 0;
}

Many thing are wrong in your code:

  1. As already well explained by other users do not use goto statement
  2. you must reset guess_value before entering the game while loop, or change the loop to a do{}while(guess_value != number)
  3. You have to add a whitespace before the %c format specifier to consume "garbage" that belongs to the input buffer after the scanf("%d", &guess_value);
  4. number variable must be init each while (answer == 'y'); loop. Otherwise it always use the same number to be guessed.

To be more specific about point 3 you must understand that the first scanf does not consume the '\n' (carriage return, enter keyboard key) char of user input. This char still in the input buffer until the second scanf is executed when '\n' is returned into answer variable. Finally when you check if (answer == 'y') the condition is always false.

LPs
  • 16,045
  • 8
  • 30
  • 61
  • i think this is the best answer. Did you run it? – Peter - Reinstate Monica Feb 17 '16 at 15:57
  • Thank you for your comment !! Helps me alot !! – Minh Feb 17 '16 at 15:58
  • Can you please explain more about the 4th point ? I am not sure that i understand it correctly. Sorry for any inconvenience. I'm not a native Ennglish speaker – Minh Feb 17 '16 at 16:17
  • @Minh Don't worry, me too. In your code you init the number to be guessed before entering the first loop. This means that the number to be guessed will be always the same, even after the user wants to play the game a second time. – LPs Feb 17 '16 at 16:20
  • ahh i understand now. Thanks for your help !! Really helpeful – Minh Feb 17 '16 at 16:24
0

avoid using goto statements. use do-while instead

do {
number=rand() %100+1;

number_of_guesses=0;
do {
    printf("\nEnter a number between 0 and 100\n");
    scanf("%d", &guess_value);      
    number_of_guesses++;
    if (guess_value == number){
        printf("Right !!! You win\n");
    }
    else if (guess_value > number){
        printf("\nYour guess is too high. Guess again");
    }
    else {printf("\nYour guess is too low. Guess again");
    }
} while (guess_value != number);

printf("You guessed %d times !", number_of_guesses);

printf("Do you want to play again? y? n?");
scanf("%c", &answer);
} while (answer == 'y');

This should fix your problem, it loops in the code until anything besides 'y' appears.

Martin Gardener
  • 1,001
  • 8
  • 14
  • This does not fix the OP problem due to the \n not consumed – LPs Feb 17 '16 at 15:21
  • I'm trying to learn C by myself so can you please explain why avoid using goto statements ? – Minh Feb 17 '16 at 15:26
  • 1
    goto is a ambigious statement, according to compiler constructor it changes the flow of instructions that you have writter ending in an incorrect manner and is a bad coding practice, anything that can be achieved using goto can in the end be achieved using a loop. – Martin Gardener Feb 17 '16 at 15:28
  • @LP i don't understand you properly mate, why would you want \n to be consumed? no one is checking for new line feed anywhere tho. – Martin Gardener Feb 17 '16 at 15:28
  • @DanyalImran Regarding the newline: When the user enters a number at `scanf("%d", &guess_value); `, the input contains a trailing newline which is not consumed immediately; scanf stops at the end of the number. As long as the number is not guessed, everything is fine because *the next* `scanf(%s)` will skip (and consume) leading whitespace, including the newline still in the buffer. (to be continued) – Peter - Reinstate Monica Feb 17 '16 at 15:42
  • oh its a typical C++ error actually that produces a buffer ignore when you shift from int to char, must be probably here aswell. – Martin Gardener Feb 17 '16 at 15:46
  • (continued) When the number is guessed properly though, the next input comes from `scanf("%c", &answer);`. The %c conversion specifier, designed to read a single char, *does not* skip leading whitespace (here: the pending newline) but instead assigns it to `answer`. The condition will never be true, no matter what the user enters (on a normal terminal, input is only transmitted after hitting enter, inserting a newline in the input). – Peter - Reinstate Monica Feb 17 '16 at 15:48
  • Sorry, I was writing my answer. BTW @PeterA.Schneider weel explained all things. – LPs Feb 17 '16 at 15:52
0

Your problem is that you should reset guess_value, otherwhise while will not be executed

Nadir
  • 1,799
  • 12
  • 20
0
#include<stdio.h>                           
#include<stdlib.h>                        //for rand & srand function
#include<time.h>                          //for time obviously. 
 int main()
{ 
int number, guess_value,number_of_guesses;
char answer;

A:                                       //put label here, Generate rand val every time. 
srand((unsigned)time(NULL));
number=rand() %100+1;

guess_value=0;                           //reset the guess value.
number_of_guesses=0;

while (guess_value != number){
  printf("\nEnter a number between 0 and 100\n");
  scanf("%d", &guess_value);      
  number_of_guesses++;
  if (guess_value == number){
    printf("Right !!! You win\n");
  }
  else if (guess_value > number){
    printf("\nYour guess is too high. Guess again");
  }
  else {printf("\nYour guess is too low. Guess again");
  }
}

printf("You guessed %d times !", number_of_guesses);
printf("Do you want to play again? y? n?");

getchar();                               //use this to remove the \n.
scanf("%c", &answer);
if (answer == 'y'){
goto A; /*return to to beginging*/
}

return 0;   
}

scanf gets the input from the input buffer, Every time a user hits the enter, \n gets to the buffer. After this scanf function, take the \n.

Joses Paul
  • 75
  • 6
-1

This works:

#include <stdio.h> // Include

int main() { 
    int number, guess_value, number_of_guesses;
    char answer;

    A:  
    srand(time(NULL)); // Fix
    number = rand() %100+1;
    number_of_guesses = 0;
    while(guess_value != number) {
        puts("\nEnter a number between 0 and 100\n");
        scanf("%d", &guess_value);      
        number_of_guesses++;
        if (guess_value == number) {
            printf("Right !!! You win\n");
        }
        else if (guess_value > number) {
            printf("\nYour guess is too high. Guess again");
        }
        else {
            printf("\nYour guess is too low. Guess again");
        }
    }

    printf("You guessed %d times !\n", number_of_guesses);
    puts("Do you want to play again? y? n?");
    scanf("%s", &answer); // Fix
    if (answer == 'y'){ 
         goto A;
    }
    return 0;   
}
AirKite
  • 1
  • 2
  • Thanks for your help !! Can you explain why we must you %s instead of %c ? – Minh Feb 17 '16 at 15:43
  • Totally [UB](https://en.wikipedia.org/wiki/Undefined_behavior). `answer` is a `char` variable. It cannot hold a sting.... – LPs Feb 17 '16 at 15:45
  • Use scanf("%s", &answer); because scanf("%c", &answer); in this code, dont work... Check it! – AirKite Feb 17 '16 at 17:58