When you type "y" with enter on your terminal, you have entered two characters. 'y' and '\n' so getchar() return '\n' on the second call. Plus getchar() return a int not a char but you stock it in char c.
#include <stdio.h> #include <stdlib.h> int main() { int c = 'y'; int n = 0; while (c == 'y') { printf("this is loop number %d\n", n); n++; printf("do you wish to continue? (y/n)"); while ((c = getchar()) == '\n' && c != EOF); } return 0; }
You can use scanf() because getchar() is very limited.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(void) { int n = 0; while (true) { printf("this is loop number %d\n", n++); printf("do you wish to continue? (y/n)\n"); char c; if (scanf(" %c", &c) != 1 || c != 'y') { break; } } }
Or:
#include <stdio.h> #include <stdlib.h> int main(void) { int n = 0; { char c; do { printf("this is loop number %d\n", n++); printf("do you wish to continue? (y/n)\n"); } while (scanf(" %c", &c) == 1 && c == 'y'); } }
getche()instead ofgetchar()scanf.cat the end?<conio.h>is, but that's Microsoft specific and won't work on another platform because it's not standardised