c语言:要求:统计文档中各类字符个数:分别统计一个文档f1.txt(自己创建一个,随手输入一些字符)中字母、数字及其字符符的个数。
时间: 2024-05-13 16:19:21 浏览: 13
以下是一个实现统计文档中各类字符个数的C语言程序:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fp;
char ch;
int letters = 0, digits = 0, others = 0;
fp = fopen("f1.txt", "r");
if (fp == NULL) {
printf("无法打开文件!\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
if (isalpha(ch)) {
letters++;
} else if (isdigit(ch)) {
digits++;
} else {
others++;
}
}
fclose(fp);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这个程序首先尝试打开名为"f1.txt"的文件,并检查打开是否成功。然后,它遍历文件中的每个字符,并使用`isalpha()`和`isdigit()`函数分别检查字母和数字。如果字符不是字母也不是数字,则计数`others`加1。最后,程序输出每个计数器的值。