Consider the following program :
#include<stdio.h>
int main(){
char c;
printf("Want to continue? :");
scanf("%c",&c);
while(c=='y')
{
printf("Want to continue? :");
scanf("%c",&c);
}
return 0;
}
What was wanted here is that the program continues till the user keeps on entering the character y
.
But it exits after the first iteration even if the user enter y
. As per my understanding, this is
happening because when I type y
I also enter a new line and so the next time scanf will fetch this
newline character instead of the character that I typed.
One way to avoid this is simply use getchar()
after each scanf so it simply eats up the new line
character. Is there any better alternative to it?