接收用户的输入信息,当用户输入完成后(cetl+d代表输入完成),自动统计用户输入的空格数、大小写字母数和其他字符数。

本文介绍了三种方法实现C语言程序,用于统计用户在命令行输入的字符,包括空格、大小写字母和其他字符的数量:while+switch/case,while+if-else,和fgets函数的应用。
摘要由CSDN通过智能技术生成

接收用户的输入信息,当用户输入完成后(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;
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值