Why is the do while loop exiting in this scenario when i enter 'y' as input character? [duplicate]

StackOverflow https://stackoverflow.com/questions/21683618

  •  09-10-2022
  •  | 
  •  

Domanda

#include <stdio.h>

int main(void) {
    char c = 'y', temp;
    printf("Press y\n");
    do {
        printf("Press y to continue\n"); // read y again and again
        scanf("%c", &c); // y entered
        printf("%c", c); // loop should repeat but doesn't repeat
    } while(c == 'y');
}
È stato utile?

Soluzione

It will not. Because scanf reads the \n character on second iteration which cause the loop to terminate. Place a space before %cto consume this \n character left behind by previous scanf.

 scanf(" %c",&c);

Altri suggerimenti

Try adding a space before %c which is a scanf quirk. The space absorbs the newline char after typing the 'y'.

        scanf(" %c",&c);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top