0

I am new with C first of all. I was trying to write a guessing game. It is simple, you are just guessing until you find the number that program holds in "no_to_guess" variable. The problem is if I turn variables to type of char program prints "Guess the number" prompt twice but when I change it back to int type it all works correctly. Do you guys have any idea?

int main(){
    int no_to_guess = 5,guess;
    
    while(guess != no_to_guess){
        printf("Guess a number: ");
        scanf("%d",&guess);
        if(guess == no_to_guess) printf("You Won");
     }
    return 0;
}

There is no problem with int type but when I change variables to char type the program prompts user twice to guess. I know using char type don't make sense but I just wonder why this is happening.

 char no_to_guess = '5',guess;
    
    while(guess != no_to_guess){
        printf("Guess a number: ");
        scanf("%c",&guess);
        if(guess == no_to_guess) printf("You Won");
}

for char type it prompts: Guess the number: Guess the number: for int type it works it supposed to be: Guess the number:

Arimfxx x
  • 3
  • 2

1 Answers1

2
  1. You need to initialize guess, or only check it after you have read some input.

  2. The format string "%c" does not ignore whitespace, unlike "%d", so you want to use format string " %c" for similar behavior.

  3. It's always a good idea to check the return value of I/O operations in particular. If scanf() fails you would be silently operating on uninitialized data.

  4. I refactored guess != no_to_guess and guess == no_to_guess into a single test (you can also print the "You Won" before the break if you prefer).

  5. Btw, in the upcoming C 2023 (or if your compiler supports the extension), instead of char guess; you could reduce duplication and ensure the same type by doing typeof(no_to_guess) guess;.

#include <stdio.h>

int main(void) {
    char no_to_guess = '5';
    for(;;) {
        printf("Guess a number: ");
        char guess;
        if(scanf(" %c", &guess) != 1) {
             printf("scanf failed\n");
             return 1;
        }
        if(guess == no_to_guess)
             break;
    }
    printf("You Won\n");
}

example session:

Guess a number: 1
Guess a number: 2
Guess a number: 5
You Won
Allan Wind
  • 23,068
  • 5
  • 28
  • 38