Problem with example 1.5.2 in K&R book on C

泄露秘密 提交于 2019-12-03 15:20:18

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.

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

Anders

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?

It would also be worth noting that Ctrl + z (which will appear as ^Z in the console) cannot simply be entered anywhere in the console input; you must enter it as the first input of your final line of string/text/characters. E.G

Picture of initial input Ctrl + z

As you can see in this example I typed in random text and after each line ended, I pressed enter. NOW THIS IS IMPORTANT!!! When you press enter on the final line it will invoke the EOF (End-of-File) and you'll get the rest of the code executing like it was originally intended to happen.

Fully executed code

Note:

  • Even though Ctrl + z appears as ^Z, it is not counted as a character by the program however many times you press it.
  • Also characters after ctrl+z are not counted.
  • Enter is counted by this program

Source: EOF in Windows command prompt doesn't terminate input stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!