2

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?

Community
  • 1
  • 1
Ravi
  • 612
  • 1
  • 6
  • 17
  • I think the newline character that gets added when you press return is getting in the way. – Bathsheba Jul 10 '15 at 12:36
  • 1
    You actually explained it pretty well, just remove "I am guessing". `scanf()` reads from the input buffer. `ungetc()` already put something there, so there's no need to wait for more input. – Paul Roub Jul 10 '15 at 12:36

2 Answers2

3

As per the man page of ungetc()

ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations.

So, basically, whatever char you enter for the first time, that is being read in c variable, and after printing, the same value is being pushed to the input buffer. Now, scanf() reads from the input buffer, so the value pushed by ungetc() is available for the next scanf() 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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

This is happening:

  • Your input: a\n
  • scanf read a leaving behind \n.
  • printf print a.
  • ungetc push back a to the input buffer and now the input is again a\n.
  • Repeat this 5 times.
haccks
  • 104,019
  • 25
  • 176
  • 264