tags:

views:

70

answers:

2

I'm teaching myself C with K&R and am stumped by one of the examples in the book. I compile the code exactly as it is written in the example but it does not do what the authors say it will. The program is supposed to count characters. The code given is as follows:

#include <stdio.h>

/* count characters in input; 1st version */
main()
{
    long nc;
    nc=0;
    while (getchar() != EOF)
     ++nc;
    printf("%ld\n", nc);
}

For it to compile I replace main() with int main(). But I assume that is not relevant to the question. The program compiles and runs fine. But it simply does not count characters as it was written to do. Am I missing something? Could something have changed in how modern compilers treat a code example such as this since the book was written? Any assistance the good folks on this message board might be able to offer would be greatly appreciated.

Best, Dan

+3  A: 

Apart from the return value of main it looks OK.

Do you do the CtrlD (Unix) or CtrlZ (Windows) at the end of input if you are entering values from keyboard?

Anders K.
+2  A: 

The program only outputs the number of character after it read an "end of file". With interactive input, you can generate an "end of file" via ctrl+d (at least on *NIX, no idea about windows). Knowing this, the program works correctly here.

Uli Schlachter
Control-Z on Windows for EOF
Jonathan Leffler