Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

kr c - Problem with example 1.5.2 in K&R book on C

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
", 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...