您的位置:首页 > 其它

从文件读取包含数字和字母字符串,统计每个字符出现的次数,将次数输出到另外一个文件

2017-03-12 10:37 1121 查看
1 //2016年重大考研机试题目
2 //从文件读取包含数字和字母字符串,统计每个字符出现的次数
3 //输出格式,字符:次数并输出到另外一个文件
4 //需要在D盘下新建文件text.in
5 #include<stdio.h>
6 #include<stdlib.h>
7 #include<string.h>
8
9 int main()
10 {
11     FILE *fp_read, *fp_write;//读写文件指针
12     int count[36]; //存储26个字母和10个数字
13     char ch;
14     int index;
15
16     memset(count, 0, sizeof(count));//初始化数组count
17
18     fopen_s(&fp_read, "D:\\text.in", "r");//打开输入文件
19     fopen_s(&fp_write, "D:\\text.out", "w");//打开写入文件
20
21     if(NULL == fp_read)
22         fprintf(fp_write, "Csn't open the input file!\n");
23
24     while(!feof(fp_read))
25     {
26         ch = fgetc(fp_read);
27         if(ch >= 'a' && ch <= 'z')//记录小写字母的次数
28             count[ch - 'a']++;
29
30         else if(ch >= 'A' && ch <= 'Z')//记录大写字母的次数
31             count[ch - 'A']++;
32
33         else if(ch >= '0' && ch <= '9')//记录数字的次数
34             count[ch - '0' + 26]++;
35     }
36
37     //输出字母到文件
38     for(index = 0; index < 26; index++)
39         if(count[index] != 0)
40             fprintf(fp_write, "%c: \t %d\n", index+97, count[index]);//根据字符的ASCII码
41     //输出数字到文件
42     for(index = 26; index < 36; index++)
43         if(count[index] != 0)
44             fprintf(fp_write, "%c: \t %d\n", index+22, count[index]);
45
46     fclose(fp_read);
47     fclose(fp_write);
48
49     system("pause");
50     return 0;
51 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐