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?
As per the man page of
ungetc()So, basically, whatever
charyou enter for the first time, that is being read incvariable, and after printing, the same value is being pushed to the input buffer. Now,scanf()reads from the input buffer, so the value pushed byungetc()is available for the nextscanf()to read it. That is why,scanf()is no asking for user input.Now, as the loop runs for 5 times, you'll encounter 5
scanf()s, all reading the first ever input data, and printing the same 5 times.That said, always check the return value of
scanf()to ensure it's success.