c语言统计一行字符中英文字母,空格,数字,其他字符的个数
#include<stdio.h>
main()
{ int a=0,b=0,c=0,d=0,e=0;
char ch;
printf("请输入一行字符:");
scanf("%d",&ch);
while((ch=getchar())!=' ')
{if(ch>='a'&&ch<='z')
a++;
else if(ch>='A'&&ch<='Z')
b++;
else if(ch>='0'&&ch<='9')
c++;
else if(ch=' ')
d++;
else
e++;}
printf("小写字母个数为:%d ",a); printf("大写字母个数为:%d ",b); printf("数字个数为:%d ",c); printf("空格个数为:%d ",d); printf("其他字符个数为:%d ",e);
}无法统计出数字和其他字符的个数,哪里错了程序中有几处问题,如下:
1. 由于使用了getchar获取标准输入的字符,所以scanf是没必要的,可以去掉。
2. getchar的返回值类型为int,所以ch最好定义为int类型。
3. 判断空格时,将“==”写成了“=”,统计会出错。
4. 可以优化的地方:main函数的返回值类型(为空则使用void)最好标明一下,规范些。一般没有特殊要求的话,最好返回值是int,默认返回0。
附上修改后的程序:
#include<stdio.h>
int main() {
int a = 0, b = 0, c = 0, d = 0, e = 0;
int ch;
while ((ch = getchar()) != ' ') {
if (ch >= 'a' && ch <= 'z')
a++;
else if (ch >= 'A' && ch <= 'Z')
b++;
else if (ch >= '0' && ch <= '9')
c++;
else if (ch == ' ')
d++;
else
e++;
}
printf("lower:%d ", a);
printf("upper:%d ", b);
printf("number:%d ", c);
printf("space:%d ", d);
printf("other:%d ", e);
return 0;
}
下一篇:这程序为何有汉字输出
上一篇:这是什么问题,代码没错。