输入一行文字,计算其中大写字母、小写字母、空格、数字及其他字符的个数。用C++实现
时间: 2023-08-13 21:06:04 浏览: 41
好的,我可以帮你解决这个问题。以下是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
string str;
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
if (isupper(ch)) {
upper++;
} else if (islower(ch)) {
lower++;
} else if (isspace(ch)) {
space++;
} else if (isdigit(ch)) {
digit++;
} else {
other++;
}
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "空格个数:" << space << endl;
cout << "数字个数:" << digit << endl;
cout << "其他字符个数:" << other << endl;
return 0;
}
```
程序中定义了变量 `upper`、`lower`、`space`、`digit`、`other` 分别表示大写字母、小写字母、空格、数字、其他字符的个数。程序首先使用 `getline()` 函数读取一行输入,然后遍历每个字符,使用 `isupper()`、`islower()`、`isspace()`、`isdigit()` 函数判断字符类型,计数器加一,最后输出各个计数器的值即可。
希望这个代码能够解决你的问题。