LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1108|回复: 7

请教一个C语言的问题,这个程序要怎么写?请大家帮忙看看!

[复制链接]
发表于 2008-8-4 23:44:46 | 显示全部楼层 |阅读模式
现在我要编的是,输入一行字符,统计里面的单词,字母,数字,空格和其它字符的个数,我的程序如下,可是一运行后就没反应了,是不是进入死循环了,但是我也看不出那问题,请大家帮忙看看。
[lhd@localhost c]$ cat check.c
#include <stdio.h>
main ()
{  int w=0,n=0,s=0,o=0,t,i,a=0;
   char c;
   printf ("请输入字符串:");
   c=getchar();
   while (c!='\n')
   { if (c>'0'&&c<'9') n++;
     if (c>'A'&&c<'Z'||c>'a'&&c<'z') a++;
     if (c==' ') {s++;t=0;}
      else if (t==0&&c>'A'&&c<'Z'||c>'a'&&c<'z')
        {t=1;
         w++;
        }
    o++;}
    o=o-n-s-a;
    printf ("统计结果:字母%d个;单词%d个;数字%d个;空格%d个;其它%d\n",a,w,n,o);
}
[lhd@localhost c]$ gcc check.c -o check
[lhd@localhost c]$ ./check
请输入字符串: I am a good man 1 2 3 ^%$#
                                                

就这样没反应了,我是初学,大家帮个忙了
发表于 2008-8-5 00:53:27 | 显示全部楼层
貌似while循环内没加c=getchar();
回复 支持 反对

使用道具 举报

发表于 2008-8-5 01:45:58 | 显示全部楼层
Post by usertesting;1882563
貌似while循环内没加c=getchar();

同意楼上的。
我无聊中,就重写了你的小程序。
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. typedef int bool;
  4. const bool false = 0;
  5. const bool true = 1;
  6. int main(int argc, char **argv)
  7. {
  8.     int c;  // 这个最好定义为 int 而不是 char
  9.     int alpha_cnt, word_cnt, digit_cnt, space_cnt, other_cnt, total_cnt;
  10.     alpha_cnt = word_cnt = digit_cnt = space_cnt = other_cnt = total_cnt = 0;
  11.     bool is_word = false;
  12.     while (true) {
  13.         c = getchar();
  14.         if (c == '\n' || c == EOF) {
  15.             if (is_word) ++word_cnt;
  16.             break;
  17.         }
  18.         if (isalpha(c)) {
  19.             ++alpha_cnt;
  20.             if (!is_word) {
  21.                 is_word = true;
  22.             }
  23.         } else if (isspace(c)) {
  24.             ++space_cnt;
  25.         } else if (isdigit(c)) {
  26.             ++digit_cnt;
  27.         } else {
  28.             ++other_cnt;
  29.         }
  30.         if (is_word && !isalpha(c)) {
  31.             is_word = false;
  32.             ++word_cnt;
  33.         }
  34.         ++total_cnt;
  35.     }
  36.     printf ("统计结果:字母%d个;单词%d个;数字%d个;空格%d个;其它%d个\n",
  37.             alpha_cnt, word_cnt, digit_cnt, space_cnt, other_cnt);
  38.     return 0;
  39. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2008-8-5 22:30:19 | 显示全部楼层
浮躁啊,晚上回来还真是没有心思看这个了,尤其是习惯了内核的编码风格,就是yichi那种就很好。

不过,还是记得K&R, P22的1.6 Arrays的例子是个很好的解答。

楼上几位都正解。
佩服yichi啊。
回复 支持 反对

使用道具 举报

发表于 2008-8-6 11:15:32 | 显示全部楼层
Post by usertesting;1882563
貌似while循环内没加c=getchar();


楼上正解阿!
回复 支持 反对

使用道具 举报

发表于 2008-8-6 15:30:27 | 显示全部楼层
应该是int c
不是char c
回复 支持 反对

使用道具 举报

 楼主| 发表于 2008-8-11 22:16:02 | 显示全部楼层
对对,搞定了,谢谢楼上的各位
回复 支持 反对

使用道具 举报

发表于 2008-8-12 00:58:31 | 显示全部楼层
好的编程的风程和习惯会帮我们大忙的,不要怕咯梭,虽然写的时候慢些,但出了问题可以很快找到问题出在哪儿
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表