#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');
}
Asked
Active
Viewed 178 times
0

ajay
- 9,402
- 8
- 44
- 71

Anish Gupta
- 293
- 1
- 5
- 18
-
Did you account for the fact that `stdin` is line buffered and the newline character will be rejected in the next iteration? – Sergey L. Feb 10 '14 at 17:15
-
This is guaranteed to be a duplicate. – alk Feb 10 '14 at 17:18
2 Answers
4
It will not. Because scanf
reads the \n
character on second iteration which cause the loop to terminate. Place a space before %c
to consume this \n
character left behind by previous scanf
.
scanf(" %c",&c);

haccks
- 104,019
- 25
- 176
- 264
2
Try adding a space before %c
which is a scanf quirk. The space absorbs the newline char after typing the 'y'.
scanf(" %c",&c);

suspectus
- 16,548
- 8
- 49
- 57