C语言:统计字符串中空格的数量。高手看看哪错了.....

2025-02-24 13:14:36
推荐回答(4个)
回答1:

scanf()函数在遇到空字符(包括空格、TAB、回车)就会结束读取,所以不能用scanf()函数从有空字符的输入流中读取字符串到数组中。你可以使用下面的语句来读取:

回答2:

scanf("%s",a)是不能一次性读取多个由空格间隔的字符串的,改为如下:

scanf("%[^\n]s",a);

回答3:

else if(a[i]=' ')

应该是

else if(a[i]==' ')

回答4:

用char a[80]有点麻烦,要用到gets(a);函数来进行输入,或者gets(a,80,'#'),就是说输入80个字符或者#之后就结束了赋值过程。
程序如下:
我用的C++哈,编译通过了。
#include
#include
void tao(char a[])
{
int b=0,c=0,d=0,e=0,i,n;
n=strlen(a);//n for the length of a
for(i=0;i {if((a[i]>='a'&&a[i]<='z')||a[i]>='A'&&a[i]<='Z')
b++; //其中的字母数
else if(a[i]>='0'&&a[i]<='9')
c++;//数字数
else if(a[i]==' ')
d++;//空格数
else e++;
}

printf("字符串中字母的个数为%d\n",b);
printf("字符串中数字的个数为%d\n",c);
printf("字符串中空格的个数为%d\n",d);
printf("字符串中其它字符的个数为%d\n",e);

}

int main()
{ char a[80];

printf("请输入一个字符串:");
gets(a);
tao(a);
system("pause");
}//空格的数量不对...........