运行结果为什么不对呀?

来源:百度知道 编辑:UC知道 时间:2024/05/11 16:57:16
统计字符中大写,小写字母,空格,数字和其他字符的个数?
#include<stdio.h>
main()
{
int big=0,small=0,space=0,number=0,other=0;
char *p;
char s[200];
printf("Please enter a string:");
gets(s);
p=s;
while(*p!='\0')
{if(*p>='a'&&*p<='z')
{small++;p++;}
if(*p>='A'&&*p<='Z')
{big++;p++;}
if(*p>=0&&*p<=9)
{number++;p++;}
if(*p==' ')
{space++;p++;}
else
{other++;p++;}
}
printf("big=%d,small=%d,space=%d,number=%d,other=%d",big,small,space,number,other);
}

1.if(*p>='0'&&*p<='9') 这里也应该是字符才行,否则你就应该用0和9所对应的ASCII码!
2.char s[200]; 这个字符数组你没有初始化,系统将随机的给它填充一些值,所以之后你通过'/0'来检测结束自然要出错!
3.你定义的是字符数组而不是string对象,所以说如果你这样输入: sdfsfsfdsdfsf
系统不能正常赋值( 或许是不严密吧),即是说你为s数组赋值的操作不能达到所要的效果。
建议你使用一个while循环来赋值,当输入一个特定字符如“#"等的时候退出,与此同时将当前数组位置填充为'\0';这样才能正确判断。
否则以你现在的做法应该这样输入才行: a b c d A B C 2 3 这样,留出空格。
4.你的程序格式很糟糕,看起来好累
5.char *p;
char s[200]; 虽然s可以赋值给p,用p访问数组效率比用s+下标访问稍微高一些,但是,这样访问会增加阅读的难度,同时稍微高的效率并不明显。所以美国有位专家Gay Horstmann推荐大家使用下标进行遍历!

源程序如下:
#include<stdio.h>
main()
{
int big=0,small=0,space=0,number=0,other=0;
char *p;
char s[200];
printf("Please enter a string:");
gets(s);
p=s;
while(*p!='\0')
{
if(*p>='a'&&*p<='z')
{small++;p++;}
else if(*p>='A'&&*p<='Z')
{
big++;p++;
}
else if(*p>='