一直都没有看由Brian W. Kernighan和Dennis M. Ritchie编写的《C程序设计语言》,今天我终于开始看这本经典的书籍。前段时间做题的时候总是有一道求单词数的题目,刚好这本书的代码和我想的不太一样,所以写一下博客~
/* 统计输入的行数、单词数与字符数 */
#include <stdio.h>
#define IN 1 /* 在单词内 */
#define OUT 0 /* 在单词外 */
int 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);
return 0;
}