C++ 语言 输入一行字符,分别统计英文字母,空格,数字和其他字符的个数。

#include<iostream>

#include<string>   //使用string类
using namespace std;
int main()
{
    string a;
    int c[4]={0,0,0,0};//定义一个数组用来存放每种字符的个数,并初始化为0
    getline(cin,a);//输入一整行元素,可以读取空格,遇到回车结束,需要包含头文件string
    //使用迭代器遍历a中的每个字符
    for(string::iterator i=a.begin();i!=a.end();i++)
    {
        if((*i>='a'&&*i<='z')||(*i>='A'&&*i<='Z'))    c[0]++;//字母
        else if(*i>='0'&&*i<='9')               c[1]++;//数字
        else if(*i==32)                c[2]++;//空格,空格的ASCII码值为32
        else                      c[3]++;//其他字符
    }
    cout<<c[0]<<" "<<c[1]<<" "<<c[2]<<" "<<c[3]<<endl;//依次输出
}
posted @ 2020-09-08 19:38  能借我十块钱吗  阅读(291)  评论(0编辑  收藏  举报