Problems with C scanf ()?

In this simple game, guessing the number scanf () does not work for the second time basically. I would really appreciate it if someone could explain why this is not working and how to fix it. Any tips on how to clear this code ?. Thanks!

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int guessed = 0;
int guesses = 0;
int total_guesses = 0;
int range_top = 1;
int generate_random_number()
{
    srand(time(NULL));
    return (rand() % range_top);
}
void take_guess(int num)
{
    int guess;
    printf("what is your guess:  ");
    scanf("%i",&guess);
    if(guess == num)
    {
        guessed = 1;
    }
    else if(guess>num)
    {
        printf("Your guess was too high,\n");
    }
    else 
    {
        printf("Your guess was too low.\n");
    }

}
int main(void)
{
    printf("This is a game in C\n");
    printf("Would you like to play? (y/n): ");
    char play;
    scanf("%c",&play);
    while(play == 'y')
    {
        printf("I am thinking of a number between 0 and %i\n",range_top);
        int num = generate_random_number();
        while(guessed ==0)
        {
            take_guess(num);
            guesses++;
        }
        printf("It took you ");
        printf("%i",guesses);
        printf(" guesses to win.\n");
        printf("Would you like to play again? (y/n): ");
        scanf("%c",&play);
        guessed = 0;
        guesses = 0;
        total_guesses+=guesses;

    }
    printf("goodbye!");
}
+4
source share
2 answers

This is a classic newbie mistake.

scanf("%c",&play);

will read the newline character that remains in the input stream after reading the number in take_guess.

Using

scanf(" %c",&play);

instead.

%c , . .

+4

scanf fflush(stdin)

-3

All Articles