C语言输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
时间: 2023-11-25 15:59:14 浏览: 42
以下是一个示例代码,可以实现输入一行字符并统计其中英文字母、数字、空格和其他字符的数量:
```c
#include <stdio.h>
int main() {
char str[100];
int i, letters, digits, spaces, others;
letters = digits = spaces = others = 0;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
i = 0;
while (str[i] != '\0') {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letters++;
} else if (str[i] >= '0' && str[i] <= '9') {
digits++;
} else if (str[i] == ' ') {
spaces++;
} else {
others++;
}
i++;
}
printf("英文字母数量:%d\n", letters);
printf("数字数量:%d\n", digits);
printf("空格数量:%d\n", spaces);
printf("其他字符数量:%d\n", others);
return 0;
}
```
首先定义了四个变量 `letters`、`digits`、`spaces` 和 `others`,分别表示英文字母、数字、空格和其他字符的数量。然后通过 `fgets()` 函数从标准输入中读取一行字符,并将其存储在 `str` 数组中。
接着使用一个 `while` 循环遍历字符数组,判断每个字符属于哪种类型,并将对应的变量加 1。最后输出各种类型字符的数量即可。