C语言编程-9_4 字符统计
时间: 2024-05-04 20:22:03 浏览: 17
这是一个简单的 C 语言程序,用于统计输入字符串中的字符数、空格数、数字数和其他字符数。
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
int ch;
int count_alpha = 0, count_space = 0, count_digit = 0, count_other = 0;
while ((ch = getchar()) != EOF)
{
if (isalpha(ch))
count_alpha++;
else if (isspace(ch))
count_space++;
else if (isdigit(ch))
count_digit++;
else
count_other++;
}
printf("Total characters: %d\n", count_alpha + count_space + count_digit + count_other);
printf("Alphabets: %d\n", count_alpha);
printf("Spaces: %d\n", count_space);
printf("Digits: %d\n", count_digit);
printf("Others: %d\n", count_other);
return 0;
}
```
程序使用 getchar() 函数逐个读取输入的字符,然后使用 isalpha()、isspace() 和 isdigit() 函数判断字符的类型,并根据类型分别累加计数器。
最后,程序输出四个计数器的值,以及所有字符的总数。
注意:程序中使用了 ctype.h 头文件中的函数,因此需要添加 #include <ctype.h> 头文件。