一个偶然的机会,我又拜读了《The_C_Programming_Language》,现在读起来感觉比以前更多了一些感觉,所以决定重新读一遍这本书,其中有一些很有用的程序比如说“单词统计程序”就是linux简单的wc命令,书中是通过“空格符”、“制表符”、“回车”来进行单词统计的,但是当输入完程序,并且编译运行的时候会发现在最后一行如果没有“Enter”,程序便会少计算一行,所以这段代码还是应该加点什么
书中代码:
#include <stdio.h> #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ /* count 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); }
|
修改后的代码:
#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){ if (c != '\n') ++nc; if (c == '\n') ++nl; if (c==' '||c=='\n'||c=='\t') state = OUT; else if (state==OUT){ state = IN; ++nw;} } if (c==EOF) ++nl; printf("\nThe number of lines:%d The number of words:%d The number of character:%d\n" ,nl,nw,nc); return 0; }
|
这样做也有一个问题,在最后一行“Enter”后会显示多统计一行,但是这样统计会比原来的代码要符合习惯一些。
阅读(1000) | 评论(0) | 转发(0) |