输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
#include <stdio.h>
int main()
{
char c;
int letters=0,space=0,digit=0,other=0;
printf("请输入一行字符:");
while ((c=getchar())!='\n')
{
if (c >= 'a'&&c <= 'z' || c >= 'A'&&c <= 'Z')
{
letters++;
}
else if (c == ' ')
{
space++;
}
else if (c >= '0'&&c <= '9')
{
digit++;
}
else
{
other++;
}
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",letters,space,digit,other);
return 0;
}
结果:
请输入一行字符:I am a student 666.
字母数:11
空格数:4
数字数:3
其他字符:1
请按任意键继续. . .
用字符函数库cctype,自己百度一下,里面有很多函数,例如isalnum(),isalpha()等等,能满足你以上要求了。
遍历一遍不行吗,根据ascII码判断
#include
#include
#include
#include
using namespace std;
int main()
{
char w[10][80]={0};
int a[4]={0};
cout << "请输入你的英文文章,每行80个字符,满了80个自动换行,最多十行" << endl;
for(int i=0;i<10;++i)
{cout<<"请输入第"<<i+1<<"行";
for(int j=0;j<80;++j)
{cin.get(w[i][j]);//此行最多储存80个字符,多的字符会自动溢出。
if (w[i][j]=='\n') {w[i][j]='\0'; break;}
}
}
for(int i=0;i<10;++i)
{
for(int j=0;j<80;++j) {//处理数据
if(w[i][j]=='\0') break;
if(w[i][j]<='Z'&&w[i][j]>='A')w[i][j]=w[i][j]-'A'+'a';
//转换大小写
if(w[i][j]<='z'&&w[i][j]>='a') a[0]+=1;//判断字母数
else if(w[i][j]<='9'&&w[i][j]>='0') a[1]+=1;//判断数字数
else if(w[i][j]==' ') a[2]+=1;//判断空格数
else a[3]+=1;
}
}
cout<<"英文字母的个数为"<<a[0]<<endl;
cout<<"数字的个数为"<<a[1]<<endl;
cout<<"空格的个数为"<<a[2]<<endl;
cout<<"其他字符的个数为"<<a[3]<<endl;
system("pause");
return 0;
}