從標準輸入讀取文本(以 EOF 結束),統計行數(\n)、單詞數(由空白字符分隔)、字符數(含換行、空格等所有字符)。
IN(在單詞內)、OUT(在單詞外)。c:nc++。c == '\n' 則行數 nl++。c 為空白(空格、制表、換行):狀態置 OUT。OUT:進入單詞,狀態置 IN,單詞數 nw++。#include <stdio.h>
#define IN 1
#define OUT 0
int main() {
int c, nl = 0, nw = 0, nc = 0, state = OUT;
while ((c = getchar()) != EOF) {
nc++;
if (c == '\n') nl++;
if (c == ' ' || c == '\t' || c == '\n')
state = OUT;
else if (state == OUT) {
state = IN;
nw++;
}
}
printf("%d %d %d\n", nl, nw, nc);
return 0;
}
輸入:
Hello world
This is a test
輸出:
2 6 27
(2 行、6 個單詞、27 字符含換行符)
fopen/fgetc)。利用簡單有限狀態機(兩態)即可在單次掃描中完成行/詞/字三項統計,時間 O(N)、空間 O(1),是經典的 K&R C 語言教程習題實現。