字数统计程序不工作。书中的代码示例 The C-programming Language Ritchie & Kernighan

Word count program not working. Code sample From the Book The C-programming Language Ritchie & Kernighan

这是字数统计程序的代码示例。但它不起作用。当我们执行它时,输入单词后应该会显示结果,但它不会生成此代码中缺少的 anything.Anything ?

#include<stdio.h>

#define IN  1 /* inside a word */
#define OUT 0 /* outside a word */

/* counts lines, words, and characters in input */

 main()
{
    int c, nl, nw, nc, state;

    state = OUT;
    nl = nw = nc = 0;
    while( (c = getchar()) != EOF ){
        ++nc;
        if( c == '\n' )
            ++nl;
        if( c == ' ' || c == '\n' || c == '\t' )
            state = OUT;
        else if( state == OUT ){
            state = IN;
            ++nw;
        }

    }
    printf("%d %d %d\n", nl, nw, nc);
}

你的代码没问题。您必须问自己如何打破 while 循环,因为它会不断读取输入,即如何将 EOF 发送到您的程序。

在 *nix 系统上,您执行 CTRL+D,在 Windows 上,您执行 CTRL+Z 以生成 EOF .

此外:使用 main() 的标准签名之一,例如 int main(void)