cwhile-loopscanfdo-whilegetchar

Why does my 'do while' loop first asks for getchar before executing printf?


I'm new to programing and trying to learn C on my own. However I've encounetred a problem I don't know how to solve. This is my simple program. Sorry for grammar mistakes english is my second language.

int main(){
    int x, confirmation;
    do{
        printf("\nTest Data: ");
        scanf("\n%d ", &x);
        printf("Do you want to stop? Y/N");
        confirmation = getchar();
       } while(confirmation != 'Y');

    return 0;
}

This is in Codeblocks btw.

When executing the program 'Test Data:' and scanf are fine but then first it asks for getchar before executing the second printf. Besides that the program works fine, when I input 'Y' in ends as it should but not before executing the second printf.

Like This: The Program

Before using getchar I used scanf("%c",...) but the problem was the same. I also tried while loop.


Solution

  • It's because it's stuck in the scanf because of the space after %d. Remove that space and then read until you get to the newline. It could look like this:

    #include <ctype.h>
    #include <stdio.h>
    
    int main(void) {
        int x, confirmation;
        int ch;
        do {
            printf("\nTest Data: ");
            if (scanf("%d", &x) != 1) break;     // no \n or space
            printf("Do you want to stop? Y/N");
    
            // read until the newline:
            while((ch = getchar()) != EOF && ch != '\n') {}
            if (ch == EOF) break;
    
            confirmation = getchar();
        } while(toupper((unsigned char)confirmation) != 'Y');
    }