C语言:输入n个字符(不超过81,回车(换行)结束),分别统计出字母,空格,数字字符,和其他字符的个数
时间: 2024-05-05 16:20:14 浏览: 12
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
int letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;
while ((ch = getchar()) != '\n') {
if (isalpha(ch)) {
letter_count++;
} else if (isspace(ch)) {
space_count++;
} else if (isdigit(ch)) {
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;
}
```
注:使用 `ctype.h` 库中的 `isalpha()`、`isspace()`、`isdigit()` 函数可以判断一个字符是否是字母、空格、数字字符。
相关问题
用C语言表示输入一行字符,以回车结束,分别统计出其中的英文字母、空格、数字和其他字符的个数
可以使用C语言中的字符数组和循环语句来实现输入一行字符,并统计其中的英文字母、空格、数字和其他字符的个数。
以下是一个示例代码:
```c
#include <stdio.h>
int main() {
char str[100]; // 定义字符数组存储输入的字符
int letter = 0, space = 0, digit = 0, other = 0;
// 分别记录英文字母、空格、数字和其他字符的个数
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin); // 读取一行字符
int i = 0;
while (str[i] != '\0') {
if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
letter++;
else if (str[i] == ' ')
space++;
else if (str[i] >= '0' && str[i] <= '9')
digit++;
else
other++;
i++;
}
printf("英文字母个数:%d\n", letter);
printf("空格个数:%d\n", space);
printf("数字个数:%d\n", digit);
printf("其他字符个数:%d\n", other);
return 0;
}
```
在上述代码中,使用了 `fgets()` 函数读取输入的一行字符,然后使用循环语句逐个判断字符的类型,并统计其个数。最后输出统计结果。
c语言输入一串字符,回车结束,分别统计数字字符、英文字母、空格和其他字符的数量并输出
可以使用以下代码来统计输入的字符中数字字符、英文字母、空格和其他字符的数量:
```c
#include <stdio.h>
int main() {
char c;
int num = 0, letter = 0, space = 0, other = 0;
printf("请输入一串字符,回车结束:\n");
while ((c = getchar()) != '\n') {
if (c >= '0' && c <= '9') {
num++;
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letter++;
} else if (c == ' ') {
space++;
} else {
other++;
}
}
printf("数字字符:%d\n", num);
printf("英文字母:%d\n", letter);
printf("空格:%d\n", space);
printf("其他字符:%d\n", other);
return 0;
}
```
在上述代码中,我们使用了一个 while 循环来逐个读入字符,直到读到回车为止。在循环中,我们判断每个字符的类型,然后分别累加数字字符、英文字母、空格和其他字符的数量。最后,我们将统计结果打印出来。