Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

character

I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this:

#include <stdio.h>

main(){
    long nc;

    nc = 0;

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

When I run the program, it opens a window I can type in, but when I hit enter all that happens is it skips down a line and I can keep typing, but I think it's supposed to print the number of characters.

Any idea what's going wrong?

like image 414
user1624005 Avatar asked Aug 26 '12 23:08

user1624005


2 Answers

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.

like image 122
ruakh Avatar answered Oct 23 '22 19:10

ruakh


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);
}
like image 36
drjd Avatar answered Oct 23 '22 18:10

drjd