使用cpp编程,输入一行字符(假设不超过200个字符),分别统计出其中的英文字母、空格、数字、其它字符的个数
时间: 2024-05-09 17:19:27 浏览: 12
```
#include<iostream>
using namespace std;
int main()
{
char str[201]; //定义字符数组,最多存200个字符
int letters=0,spaces=0,digits=0,others=0;
cout<<"请输入一行字符:"<<endl;
cin.getline(str,201); //输入一行字符,使用getline函数
for(int i=0;str[i]!='\0';i++)
{
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) //判断是否为字母
letters++;
else if(str[i]==' ') //判断是否为空格
spaces++;
else if(str[i]>='0'&&str[i]<='9') //判断是否为数字
digits++;
else //其他字符
others++;
}
cout<<"字母个数:"<<letters<<endl;
cout<<"空格个数:"<<spaces<<endl;
cout<<"数字个数:"<<digits<<endl;
cout<<"其他字符个数:"<<others<<endl;
return 0;
}
```
相关问题
输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数C++
以下是C++统计字符串中英文字母、数字、空格和其他字符个数的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str); // 输入字符串
int letter = 0, digit = 0, space = 0, other = 0;
for (int i = 0; i < str.length(); i++) {
if (isalpha(str[i])) { // 判断是否为字母
letter++;
} else if (isdigit(str[i])) { // 判断是否为数字
digit++;
} else if (isspace(str[i])) { // 判断是否为空格
space++;
} else { // 其他字符
other++;
}
}
cout << "字母个数:" << letter << endl;
cout << "数字个数:" << digit << endl;
cout << "空格个数:" << space << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
输入一行字符,分别统计其中大写英文字母,小写英文字母,空格,数字,和其他字符的个数。
```cpp
#include <iostream>
using namespace std;
int main() {
char c;
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
while(cin.get(c)) {
if(c >= 'A' && c <= 'Z') {
upper++;
} else if(c >= 'a' && c <= 'z') {
lower++;
} else if(c == ' ') {
space++;
} else if(c >= '0' && c <= '9') {
digit++;
} else {
other++;
}
}
cout << "大写英文字母个数:" << upper << endl;
cout << "小写英文字母个数:" << lower << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
--相关问题--:
1. 如何统计一个字符串中某个字符的个数?
2. 如何判断