单词计数
下面是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);
}
验证结果:
跟系统wc统计数一样
评论区