Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26395
  • 博文数量: 5
  • 博客积分: 225
  • 博客等级: 二等列兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 23:29
文章分类

全部博文(5)

文章存档

2008年(5)

我的朋友
最近访客

分类: C/C++

2008-08-16 00:41:38

一个偶然的机会,我又拜读了《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) |
0

上一篇:getchar()函数的使用

下一篇:没有了

给主人留下些什么吧!~~