统计文本文件中各类字符个数: 分别统计一个文本文件中字母、数字及其他学符的个数。试编写相应程序。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
FILE *fp = fopen("test1.txt","r");
char ch;
int word_cnt = 0, num_cnt = 0,others_cnt = 0;
if(!fp){
printf("file read error\n");
exit(0);
}
while((ch = fgetc(fp))!=EOF){ //用EOF作为控制条件比feof()要好,feof()会多统计一个EOF文件结束符
//while(!feof(fp)){
//ch = fgetc(fp);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
word_cnt++;
else if(ch>='0'&&ch<='9')
num_cnt++;
else if(ch == '\n') //多行文本的字符统计一定要把换行符排除掉
continue;
else
others_cnt++;
}
printf("words:%d ,number:%d ,others:%d\n",word_cnt,num_cnt,others_cnt);
if(fclose(fp)){
printf("file close error\n");
exit(0);
}
return 0;
}