Although the other answers are technically correct, I feel that this example (1.5.2) and the following one (1.5.3) are pedagogically confusing. Just google "character counting 1.5.2" and you will find many others who got caught up by this example, just as the OP did. The reason it is so confusing is that there is no explanation in the text about how to generate the EOF character in interactive mode, AND the previous examples outputted the results as soon as "return" was entered. Thus, any beginner to C would assume that the program in 1.5.3 should do the same...
I would like to propose the following alternative code, which produces the expected result:
#include <stdio.h>
#define EOL '
'
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
", nc-1);
nc = 0;
}
}
}
The only element of C not already explained in the text is the if
statement, which is actually explained in the very next section (1.5.3). I hope this small alternative example will serve to help others who got caught up by the original example from the K&R book. A good "Exercise 1.7b" would be to examine the differences between the two versions and explain verify that they output the same results (after reading about CtrlD / CtrlZ from the other answers).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…