Search code examples
cprintfgetchar

getchar() taking stuff which I print using printf()


#include <stdio.h>

int main() {
  int c;
  for (int i = 0; i < 10; i++) {
    c = (getchar() != EOF);
    printf("%d\n", c);
  }
  printf("As we can see, the value of c is either 0 or 1 (as claimed in the "
         "book)\n");
  return 0;
}

I wrote this code in C to show that c = (getchar() != EOF) is either 0 or 1. However, when I run the code, and I type let's say 1, it prints 1 two times. When I press Ctrl-D , which prints the EOF character, it just prints 0 for the remaining iterations of the loop.

So , I tried to get rid of the loop, and run the code inside the loop one-time, and it works fine. I suspect that getchar() is reading the stuff which I am printing using printf() . If that is so, what is it I should do for getchar() to ignore that stuff?

Thanks


Solution

  • You are not only typing 1. (We know this because, in common user interfaces, pressing the 1 key does not immediately send a “1” character to the program unless special arrangements are made. So, if you just pressed the 1 key, the program would not respond.) You are likely pressing the 1 key and the Return or Enter key.

    When you press the 1 key, the character “1” is recorded in a buffer. When you press the Return or Enter key, a newline character is added to the buffer, and then the contents of this buffer are sent to the program.

    The program’s first execution of getchar gets the ”1” character. The program’s second execution of getchar gets the newline character.

    Additionally, pressing Control-D does not directly send an EOF indication.