简体   繁体   English

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

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

This is the code sample for the word counting program.这是字数统计程序的代码示例。 But it's not working.但它不起作用。 When we execute it, after entering words it is supposed to display the results, but it is not producing anything.Anything missing in this code ?当我们执行它时,输入单词后它应该显示结果,但它没有产生任何东西。这段代码中缺少什么吗?

#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);
}

Your code is fine.你的代码没问题。 You have to ask yourself how to break the while loop as it continuously reading input ie how to send EOF to your program.您必须问自己如何打破 while 循环,因为它不断读取输入,即如何将EOF发送到您的程序。

On *nix systems, you do CTRL+D and on Windows you do CTRL+Z to generate EOF.在 *nix 系统上,您执行CTRL+D,而在 Windows 上,您执行CTRL+Z以生成 EOF。

Also: use one of standard signature for main() such as int main(void) .另外:使用main()的标准签名之一,例如int main(void)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM