网站首页 网站地图
网站首页 > 爱情文案 > 一个c语言程序关于输入一行字符分别统计出其中

一个c语言程序关于输入一行字符分别统计出其中

时间:2025-03-31 21:49:20

```c

include

include

int main() {

char str;

int letters = 0, spaces = 0, digits = 0, others = 0;

printf("请输入一行字符(按回车键结束):\n");

fgets(str, sizeof(str), stdin);

for (int i = 0; str[i] != '\0'; i++) {

if (isalpha(str[i])) {

letters++;

} else if (isspace(str[i])) {

spaces++;

} else if (isdigit(str[i])) {

digits++;

} else {

others++;

}

}

printf("字母:%d个

", letters);

printf("空格:%d个

", spaces);

printf("数字:%d个

", digits);

printf("其他字符:%d个

", others);

return 0;

}

```

代码说明:

输入处理

使用 `fgets` 函数读取一行输入,`fgets` 可以处理包含空格的字符串。

字符分类统计

使用 `isalpha` 函数判断是否为字母(不区分大小写);

使用 `isspace` 函数判断是否为空格;

使用 `isdigit` 函数判断是否为数字;

其他字符直接归类为 `others`。

输出结果

最后使用 `printf` 函数输出各类字符的统计结果。

注意事项:

该程序假设输入字符串长度不超过99个字符(留一个位置给终止符 `\0`),实际使用中可根据需要调整数组大小。

`fgets` 会读取换行符,如果不需要换行符,可以使用 `strcspn` 函数去除。

通过这个程序,可以方便地统计任意输入字符串中不同类型字符的分布情况。