简体   繁体   中英

Do-While loop in C

I recently started working with C programming language, about two or three days ago, but I encountered some problem when working with the do-while loop, This is part of my program that would not run.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main(void){        
    char another_game   =   'Y';
    scanf("%c", &another_game);
    do{
        printf("\nWould you like to continue(Y/N)?");
        scanf("%c", &another_game);
    }while(toupper(another_game) == 'Y');
    return 0;
}

The loop is suppose to continue running as long as the user types 'Y' or 'y' when prompt to do so, but I noticed that after the program executes the loop the first time it just displays the question again and then the loop breaks. I tried using integers, for the user to type 1 when he wishes to continue or 0 when he wishes to quit, it worked, so I do not understand why this one would not. I would appreciate all help on solving this issue, thanks

Because when you press <enter> , there's the trailing newline character in the stdin buffer. Better use fgets() instead:

char buf[0x10];
fgets(buf, sizeof(buf), stdin);
if (toupper(buf[0]) == 'Y') {
    // etc.
}

I would use getchar as it would be more deterministic for your purposes. Also be sure to add one more getchar to check for newline character.

do { printf("enter Y/N\\n"); } while( ( (toupper(getchar()) == 'Y') + (getchar() == '\\n') ) == 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM