getchar

getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of file) is returned instead. It is therefore usual to compare this value against EOF before using it. If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly.

As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control - d.


  #include <stdio.h>

  main()
  {   int ch, i = 0;

      while((ch = getchar()) != EOF)
          i ++;

      printf("%d\n", i);
  }

  Go to Character I/O     Go to Index               Go to putchar