Search code examples
cgetchar

Why is getchar() not working for me?


I've just started programming c and I'm working through The C Programming Language by Brian W.Kernighan and Dennis M.Richie.

One of the first examples is character counting and the following program is given, but when I enter a string no result it printed.

#include <stdio.h>

main()
{
   long nc;

   nc = 0;
   while (getchar() != EOF)
          ++nc; 
   printf("%ld\n",nc);
 }

Why isn't this working?


Solution

  • You have to finish the input. Your program will count characters until EOF is encountered. EOF, in the keyboard, can be sent by pressing Ctrl-Z then ENTER if you are in Windows, or Ctrl-D then ENTER if you are in Linux/OS X.