Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yes/No loop in C

I just don't understand why this Yes/No loop will not work. Any suggestions? Given the input is "Y". I just want it to run the loop, then ask for Y or N again. If Y, print success, if N, print a good bye statement. What's the reason?

int main(){
    char answer;
    printf("\nWould you like to play? Enter Y or N: \n", answer);
    scanf("%c", &answer);
    printf("\n answer is %c");
    while (answer == 'Y'){
        printf("Success!");

        printf("\nDo you want to play again? Y or N: \n");
        scanf("%c", &answer);
    }
    printf("GoodBye!");
    return 0;
}
like image 418
user2232926 Avatar asked Aug 14 '26 15:08

user2232926


2 Answers

Change the second scanf to:

scanf(" %c", &answer);
//     ^

The problem is, when you enter Y and press ENTER, the new line is still in the input buffer, adding a space before %c could consume it.

like image 108
Yu Hao Avatar answered Aug 16 '26 19:08

Yu Hao


fixed the various issues

#include <stdio.h> 
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
while (answer == 'Y'){

printf("Success!");

printf("\nDo you want to play again? Y or N: \n");

scanf(" %c", &answer);
printf("\n answer is %c\n", answer);

}
printf("GoodBye!");
return 0;
}
like image 22
Keith Nicholas Avatar answered Aug 16 '26 19:08

Keith Nicholas