Search code examples
cstdio

Why is this program going into an infinite loop after the first scanf?


I am trying to get the program to allow the user to input a number and then have the computer tell the user if the number is too small, too big, or equal to a randomly generated number. The prompt and input work, but it gets stuck after the first scanf.

I think it has to do with scanf and not the conditionals, because I added printf("Testing stopping point") and that doesn't get printed to the user's screen. What am I doing wrong?

#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>

int main()
{
        //Generate a random number
        int n = 1;
        int count = 0;
        int randomNumber;
        srand(time(NULL));

        for (int i = 1; i <= n; i++)
        {
                randomNumber = rand() % 101;
        }

        printf("Guess a number between 1 - 100: ");

        int input;
        scanf("%d\n",&input);

        printf("Testing stopping point");

        do
        {
            if (input > randomNumber)
            {
                count +=1;
                printf("Too large!Try again: ");
                getchar();
            }else if (input < randomNumber)
            {
                count += 1;
                printf("Too small!Try again: ");
                getchar();
            }
        }while (input != randomNumber);

        if(input == randomNumber)
        {
            count +=1;
            printf("Correct!\n");
            printf("You guessed %d times\n", count);
            return 0;
        }
}

Solution

  • You have to remove the \n in the scanf,try like this:

    #include <stdio.h>
    #include <stdbool.h>
    #include <time.h>
    #include <stdlib.h>
    
    int main()
    {
            //Generate a random number
            
            int count = 0;
            int randomNumber;
            srand(time(NULL));
            randomNumber = (rand() % 101)+1;
            int input=-1;
          
            while (input != randomNumber)
            {
                  printf("Guess a number between 1 - 100: ");
                 scanf("%d",&input);
                if (input > randomNumber)
                {
                    count +=1;
                    printf("Too large!Try again: ");
                    
                }else if (input < randomNumber)
                {
                    count += 1;
                    printf("Too small!Try again: ");
                   
                }
             
            }
    if(input == randomNumber)
            {
                count +=1;
                printf("Correct!\n");
                printf("You guessed %d times\n", count);
               
            }
    
           return 0; 
    }