Character Counter from "The C Programming Language" Not Working As I Expected

This line:

while (getchar() != EOF)

means that it keeps reading until the end of input — not until the end of a line. (EOF is a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.


If you want to terminate on EOL (end of line), replace EOF with '\n':

#include <stdio.h>

main(){
    long nc;

    nc = 0;

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

Enter is not EOF. Depending on your OS, Ctrl-D or Ctrl-Z should act as EOF on standard input.

Tags:

C

Character