使用c++编程,输入一行字符(假设不超过200个字符),分别统计出其中的英文字母、空格、数字、其它字符的个数
时间: 2024-05-03 15:21:23 浏览: 10
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[201];
int letter = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符(不超过200个):\n");
fgets(str, 201, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
letter++;
} else if (isspace(str[i])) { // 判断是否为空格
space++;
} else if (isdigit(str[i])) { // 判断是否为数字
digit++;
} else { // 其它字符
other++;
}
}
printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其它字符个数:%d\n", letter, space, digit, other);
return 0;
}
```
相关问题
c++输入一行字符(假设不超过200个字符),分别统计出其中的英文字母、空格、数字、其它字符
#include <stdio.h>
#include <ctype.h>
int main() {
char str[201];
int i, letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;
printf("请输入一行字符(不超过200个字符):");
fgets(str, 201, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letter_count++;
} else if (isspace(str[i])) {
space_count++;
} else if (isdigit(str[i])) {
digit_count++;
} else {
other_count++;
}
}
printf("英文字母个数:%d\n", letter_count);
printf("空格个数:%d\n", space_count);
printf("数字个数:%d\n", digit_count);
printf("其它字符个数:%d\n", other_count);
return 0;
}
C加加循环结构输入一行字符不超过200个分别统计其中英文字母空格数字其他字符的个数
以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
char str[201]; // 存储输入的字符串
int letter = 0, space = 0, digit = 0, other = 0; // 统计各类字符的个数
cout << "请输入一行字符(不超过200个):" << endl;
cin.getline(str, 201); // 读取一行字符串
// 循环遍历字符串中的每个字符
for (int i = 0; str[i] != '\0'; 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;
}
```
说明:
- 使用 `cin.getline()` 函数读取一行字符串,存储到字符数组 `str` 中;
- 循环遍历字符数组 `str` 中的每个字符,使用 `isalpha()`、`isspace()`、`isdigit()` 函数判断字符类型;
- 使用计数器变量 `letter`、`space`、`digit`、`other` 统计各类字符的个数;
- 输出结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)