接收用户的输入信息,当用户输入完成后(cetl+d代表输入完成),自动统计用户输入的空格数、大小写字母数和其他字符数。
用前两种方法做这个题是非常容易想到的,用fgets函数这种方式我觉得非常的巧妙,就把它们都分享出来给像我这样的初学者来看看拓展一下思路。
方法一:用while加switch
int main()
{
int count_space=0;//空格数
int count_letter=0;//字母数
int count_other=0;//其他字符数
char n;
puts("Please enter character sthring:");
while ((n=getchar())!= EOF)//循环取字符,遇到EOF结束
{
switch (n)
{
case ' ':
count_space++;
break;
case 'a'...'z': //这里也可以改为大小写字母的数
count_letter++;
break;
case 'A'...'Z':
count_letter++;
break;
default:
count_other++;
break;
}
}
printf("\n空格数为:%d\n字母数为:%d\n其他符号数为:%d\n",count_space,count_letter,count_other);
return 0;
}
方法二:用while加if eles
int main()
{
int count_space=0;
int count_letter=0;
int count_other=0;
char n;
puts("Please enter character sthring:");
while ((n=getchar())!= EOF)
{
if(n==' ')
count_space++;
else if((n>='A')&&(n<='Z')||(n>='a')&&(n<='z'))
count_letter++;
else
count_other++;
}
printf("\n空格数为:%d\n字母数为:%d\n其他符号数为:%d\n",count_space,count_letter,count_other);
return 0;
}
方法三:用fgets
int main()
{
int count_space=0;
int count_letter=0;
int count_other=0;
char n[10000]={0};/*定义一个最大长度为9999, 末尾是'\0'的字符数组来存储字符串,并初始化为0*/
puts("Please enter character sthring:");
fgets(n,10000,stdin);/*从输入流stdin即输入缓冲区中读取10000个字符到字符数组n中*/
for(int i=0;i<strlen(n);i++)
{
if (n[i]==EOF)
break;
if(n[i]==' ')
count_space++;
else if((n[i]>='A')&&(n[i]<='Z')||(n[i]>='a')&&(n[i]<='z'))
count_letter++;
else
count_other++;
}
printf("\n空格数为:%d\n字母数为:%d\n其他符号数为:%d\n",count_space,count_letter,count_other);
return 0;
}