Discussion
Consider the statements
putchar ( getchar ( ));
putchar(getchar( ));
if
a
b
is the input, the output will be
Answer: B
Correct answer: a followed by a newline; b is never read
The trap is that the newline is itself a character in the input stream. Typing a, Enter, b, Enter puts four characters into stdin: ’a’, ’\n’, ’b’, ’\n’. getchar reads one character at a time and does not skip whitespace, so the first putchar(getchar()) reads and prints a, and the second reads the newline and prints it. The b is still sitting in the buffer when the program ends. The output is therefore the letter a followed by a line break - not ab, which would require the input to be typed as a single line ab, and not a b, which would need a space between them. This is the reason scanf("%d") followed by getchar() so often appears to skip an input: the newline left behind by the earlier read is consumed by the later one. The keyed option in this record read “this can’t be the input”, which describes nothing; its text has been corrected to the actual output.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development