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:
>Solution :
-
You need to initialize guess, or only check it after you have read some input.
-
The format string
"%c"does not ignore whitespace, unlike"%d", so you want to use format string" %c"for similar behavior. -
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. -
I refactored
guess != no_to_guessandguess == no_to_guessinto a single test (you can also print the "You Won" before thebreakif you prefer). -
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 doingtypeof(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