编程实现从键盘随机的输入一串字符(不超过100个),统计出其中英文字母、数字和其它字符的个数并输出。
时间: 2024-03-26 07:34:30 浏览: 37
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
int main() {
const int MAX_LEN = 100;
char str[MAX_LEN + 1];
cin.getline(str, MAX_LEN + 1);
int num_alpha = 0, num_digit = 0, num_other = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
num_alpha++;
} else if (isdigit(str[i])) {
num_digit++;
} else {
num_other++;
}
}
cout << "Alphabets: " << num_alpha << endl;
cout << "Digits: " << num_digit << endl;
cout << "Others: " << num_other << endl;
return 0;
}
```
代码中首先定义了一个常量 `MAX_LEN` 表示输入字符串的最大长度,然后定义了一个字符数组 `str`,使用 `cin.getline()` 从键盘读入字符串。接下来使用循环遍历字符串,对于每个字符判断其是否是字母、数字或其它字符,并统计个数。最后输出结果。其中用到了 C++ 标准库中的 `isalpha()` 和 `isdigit()` 函数,分别用于判断字符是否是字母和数字。