Home > OS >  Scanf is causing infinite loop
Scanf is causing infinite loop

Time:03-11

I have a C program for Guess the number game but when I run this code it goes into infinite loop, I think it's because of scanf() in the 11th line! How can I fix this?

#include <stdlib.h>
#include <time.h>
int main(){
    int number, guess, nguesses = 1;
    char name;
    srand(time(0));
    number = rand()0   1; // Generates a random number between 1 and 100
    // Keeps running the loop until the number is guessed
    printf("------| Welcome to Guess the number game |-------\n");
    printf("Enter your name: ");
    scanf("%c", name); ---> Causing infinite loop

    do
    {
        printf("\nGuess the number between 1 to 100\n");
        scanf("%d", &guess);
        if(guess>number)
        printf("Lower number please!\n");
        else if(guess<number)
        {
            printf("Higher nummber please!\n");
        }
        else
        {
            printf("Congratulations you have correctly guessed the number!\nAttempts taken: %d\n", nguesses); 
        }
        nguesses  ;
    } 
    while (guess!=number);
    return 0;
}

CodePudding user response:

enter image description hereWhen you declare name, you signed it for char but names has no only one character. So it must be an array, and while you scanf, you use %s instead of %c. (%c for char, %s for char array{you can think like string}). I tried what ı wrote in here and enjoyed your game.

char name[10]; //or any number
scanf("%s", name);
  •  Tags:  
  • c
  • Related