2.输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数。C++
时间: 2023-11-23 22:53:29 浏览: 151
这是一个统计字符类型个数的问题,可以使用C++中的字符处理函数和循环语句来实现。具体步骤如下:
1.定义变量分别用于存储英文字母、空格、数字和其他字符的个数,初始值都为0。
2.使用getline()函数读取一行字符,存储到一个字符串变量中。
3.使用for循环遍历字符串中的每个字符,判断其类型并更新对应的计数器。
4.输出各个计数器的值。
下面是代码实现:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int letter = 0, space = 0, digit = 0, other = 0;
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
if (isalpha(str[i])) {
letter++;
} else if (isspace(str[i])) {
space++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
}
cout << "英文字母个数:" << letter << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
阅读全文
相关推荐















