Although the other answers are technically correct, I believe that this example (1.5.2) and the next (1.5.3) are pedagogically confusing. Just google "character counting 1.5.2" and you will find many others who have been picked up by this example, just like the OP did. The reason this is so confusing is that there is no explanation in the text on how to generate the EOF symbol interactively, and the previous examples output the results immediately after entering "return". So any newbie in C would suggest that a program in 1.5.3 should do the same ...
I would suggest the following alternative code that gives the expected result:
#include <stdio.h> #define EOL '\n' main() { long nc; int c; nc = 0; while ((c = getchar()) != EOF) { ++nc; if (c == EOL) { /* Print number of input characters (not including return character) */ printf("%ld\n", nc-1); nc = 0; } } }
The only C element that is not already explained in the text is the if , which is actually explained in the next section (1.5.3). I hope this small alternative example serves to help others keen on the original example from K & R. A good βExercise 1.7bβ would be to study the differences between the two versions and explain that they produce the same results (after reading about Ctrl D / Ctrl Z from other answers).
source share