In C, what happens with ungetc and which stream does it apply to? Consider the program below when the user provides the character 'b' as input each time.\n\n#include<stdio.h>\n\nint main()\n{\n int i;\n char c;\n for(i=1; i<=5; i++)\n {\n scanf("%c", &c); /* given input is 'b' */\n ungetc(c, stdout);\n printf("%c", c);\n ungetc(c, stdin);\n }\n return 0;\n}\n\nChoose the best description of the visible output.

Difficulty: Medium

Correct Answer: bbbbb

Explanation:


Introduction / Context:
ungetc pushes a character back onto an input stream, so it will be returned by the next read from that same stream. It is only valid for input streams such as stdin, not for output streams like stdout.



Given Data / Assumptions:

  • The loop runs 5 times.
  • scanf("%c", &c) reads one character from stdin each iteration.
  • ungetc(c, stdout) is invalid usage but typically just fails (returns EOF) without affecting stdout's printed content.
  • printf("%c", c) prints the character read.
  • ungetc(c, stdin) pushes that same character back to stdin so the next scanf reads it again.


Concept / Approach:
Because the character is pushed back to stdin at the end of each iteration, the next iteration reads the same character again. The misuse of ungetc on stdout does not alter what gets printed.



Step-by-Step Solution:
Iteration 1: read 'b', print 'b', push back 'b'.Iteration 2..5: each time scanf reads the previously pushed-back 'b', prints 'b', and pushes back 'b' again.Total printed characters: 5 b's.



Verification / Alternative check:
Remove the ungetc(c, stdout) line; the output behavior will be the same. The key is ungetc(c, stdin).



Why Other Options Are Wrong:
bbbb / b: incorrect counts.Error in ungetc statement.: Even though ungetc on stdout is incorrect, many implementations won't crash, and the question focuses on what gets printed.



Common Pitfalls:
Thinking ungetc affects output streams; forgetting that ungetc only affects the very next read on the same input stream.



Final Answer:
bbbbb

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion