Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the statements
putchar ( getchar ( ));
putchar(getchar( ));
if
a
b
is the input, the output will be

  • A.an error message
  • B.a followed by a newline; b is never read
  • C.ab
  • D.a   b

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.