c++ 编写程序输入一个以回车结束的字符串(小于80个字符)分别统计其中英文字母、数字、其他字符的个数
时间: 2024-01-09 22:53:50 浏览: 32
下面是一个简单的 C++ 程序,可以实现输入一个以回车结束的字符串,并统计其中英文字母、数字、其他字符的个数:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
const int MAX_LEN = 80;
char str[MAX_LEN];
cin.getline(str, MAX_LEN); // 读入字符串
int letter_cnt = 0, digit_cnt = 0, other_cnt = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) {
letter_cnt++;
} else if (isdigit(str[i])) {
digit_cnt++;
} else {
other_cnt++;
}
}
cout << "英文字母个数:" << letter_cnt << endl;
cout << "数字个数:" << digit_cnt << endl;
cout << "其他字符个数:" << other_cnt << endl;
return 0;
}
```
程序中使用 `cin.getline()` 函数读入字符串,`strlen()` 函数获取字符串长度,`isalpha()` 和 `isdigit()` 函数判断字符类型。最后输出统计结果。