从一个文本文件中找出使用频率最高的五个字符

 1 #include <stdio.h>
 2 #define N 95    //可打印字符总数
 3 #define space 32 //空格符ASCII码
 4 
 5 int main()
 6 {
 7     char cNum[N] = {0}, ch;
 8     int iNum[N] = {0};
 9     int i, j, k, iMax, tag, h = 5;
10     
11     FILE* fp = fopen("file.txt", "r");
12     if(NULL == fp)
13     {
14         printf("file open fail");
15         return -2;
16     }
17     for(i=0; i<N; i++)
18     {
19         cNum[i] = space + i;
20     }
21     while(!feof(fp))    //当文件结束,feof(FILE* fp)函数非零值,如果没有结束,返回0
22     {
23         ch = ::fgetc(fp);
24         for(j=0; j<N; j++)
25         {
26             if(cNum[j] == ch)
27             {
28                 iNum[j]++;
29                 break;
30             }
31         }
32     }
33     while(h>0)
34     {
35         iMax = iNum[0];
36         for(k=0; k<N; k++)
37         {
38             if(iNum[k] > iMax)
39             {
40                 iMax = iNum[k];
41                 tag = k;
42             }
43         }
44         printf("%d %c
", iMax, cNum[tag]);
45         iNum[tag] = 0;    //把对象最多个数的字符 对应的次数iNum[tag]清空,以继续找出第二多的字符数。 
46         h--;
47     }
48 }
原文地址:https://www.cnblogs.com/qq702368956/p/4850606.html