目 录CONTENT

文章目录

UNIX系统wc命令 c语言实现

不争
2024-01-02 / 0 评论 / 0 点赞 / 45 阅读 / 1694 字

单词计数

下面是UNIX系统wc程序骨干部分:

#include<stdio.h>
#define IN 1  //在单词内
#define OUT 0 //在单词外

void main(void){
    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);
}

验证结果:

image-20220423210058544

跟系统wc统计数一样

0

评论区