字数统计程序不工作,代码示例摘自《C编程语言》里奇和克尼汉

c0vxltue  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(71)

这是单词计数程序的代码示例。但它不工作。当我们执行它时,在输入单词后,它应该显示结果,但它没有产生任何东西。这段代码中缺少什么吗?

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

字符串

ajsxfq5m

ajsxfq5m1#

你的代码是好的。你必须问自己如何打破while循环,因为它不断阅读输入,即如何发送EOF到你的程序。
在 *nix系统上,您可以使用CTRL+D,在Windows上使用CTRL+Z来生成命令。
另外:使用main()的标准签名之一,例如int main(void)

qnyhuwrf

qnyhuwrf2#

这是我的版本这个程序在K&R计数其他字符,以及但我的版本只计数字符,这只是字母表。是的,你必须按Ctrl+d发送信号到这个程序执行printf语句后,而循环。

#include<stdio.h>
int main(){
    int c = 0;    // input variable
    int lc = 0;   // line count
    int wc = 0;   // word count
    int cc = 0;   // char count
    int state = 0;// check space after word
    while((c = getchar()) != EOF){
        if(c == '\n'){
            ++lc;
        }
        if((c == ' ' || c == '\t' || c == '\n') && state == 1){
            ++wc;
            state = 0;
        }
        else if((c >= 'A' || c>= 'a') && (c <='Z' || c <= 'z'){
        //this is to count only character between A or a and Z or z
            ++cc;
            state = 1;
        }
    }
    printf("lc = %d\twc = %d\tcc = %d\n",lc,wc,cc);
}

字符串

相关问题