2023-04-29

Making a guessing game in C but outputs are different when I change variable types [duplicate]

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:



No comments:

Post a Comment