Search code examples
cgetcharkernighan-and-ritchie

The program compiles, but when provided with an input, does nothing


I'm a beginner programmer (forgive this very basic question), and I am learning C through the Kernighan and Ritchie book "The C programming language".

I copied this program from the book, and it compiles fine, but when an input is given, the program does nothing.

#include <stdio.h>

int main() {
   long nc;

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

The output is supposed to be the number of characters in the input, but nothing is happening


Solution

  • It will print the number of inputted characters when it has encountered the EOF (=end of file) condition.

    If you're providing input through a terminal, there's no natural end of file so you need to signal it with a special keyboard shortcut, which is typically either Ctrl+Z on Windows and Ctrl+D on a Unix system (Linux, MacOs, ...). (Windows also appears to require that you type an Enter both before and after the Ctrl+Z. The new-line character before the Ctrl+Z counts as another character, which effectively means that Windows, unlike Unixes, doesn't appear to allow you to have text-files that don't end with a new-line, at least with mingw gcc without cygwin.)

    If you provide the input file through redirection as in ./a.out < some_file, then you don't have to worry about that because filesystem files have natural ends.