Search code examples
cchargetchar

Exercise 1-6: (page 17 K&R) - getchar() question


When I run the program below, output give second 1. I debug the program, but I couldn't understand why compiler writing second 1 anytime?

output like this.

#include <stdio.h>

main()
{
int c;

while (c = getchar() != EOF)
    printf("%d\n", c);
printf("%d - at EOF\n", c);
}

Solution

  • The Enter key you press to "send" the input from the terminal to the program is added in the input buffer as a newline '\n', which will be read in the second iteration of the loop.