I am not understanding how this program works?
char c;
int i;
for(i=1;i<=5;i++)
{
scanf("%c",&c);
printf("%c",c);
ungetc(c,stdin);
}
The output of the program is- character which is entered first time is printed 5 times.
a
aaaaa
According to SO post What is the difference between putc and ungetc? ungetc
puts something back into the input buffer.
So in this program during the first iteration scanf()
accepts input from the keyboard and printf()
displays it and then ungetc()
pushes back the same character into the input buffer.
But during the second iteration no input is being accepted, so I am guessing printf()
prints the character which was pushed into the input buffer by ungetc()
.
Can someone explain in clear manner how exactly this program works?