- //C++file.cpp
- /*为实现统计字符
- 给定字符集G{大小写字母∪( ) , . 和space}共26*2+5=57种字符
- 先用标准字符集给G赋初值
- 将待统计的文章放入article中,用*号标识文章结尾
- 统计时用标准字符集与待统计字母集比对相等时
- */
- #include <fstream>
- #include <iostream>
- #define MAX_CHARS_NUM 58
- #define MAX_ROW 100
- #define MAX_COL 100
- using namespace std;
- char chars[MAX_CHARS_NUM];//存储文章中出现的字符,字符集
- char article[MAX_ROW][MAX_COL];//存储待统计文章
- int frequence[MAX_CHARS_NUM] = {0};//各字符出现的频度,为计算字符概率
- double probty[MAX_CHARS_NUM];//各字符出现的概率
- void initchars(ifstream &_fin)
- {
- for(int i = 0; i < MAX_CHARS_NUM; i++)
- _fin.get(chars[i]);
- }
- void show(char *ch)
- {
- for(int i = 0; i < MAX_CHARS_NUM; i++)
- cout << ch[i];
- cout << endl;
- }
- void show(char *ch, int *fre)
- {
- for(int i = 0; i <MAX_CHARS_NUM; i++)
- cout << ch[i] << "/t" << fre[i] << endl;
- }
- void show(char (*art)[MAX_COL])
- {
- for (int i = 0; i < MAX_ROW; i++)
- {
- for (int j = 0; j < MAX_COL; j++)
- {
- cout << art[i][j];
- if(art[i][j] == '*')break;//遇到文章结尾
- }
- if(art[i][j] == '*')break;//遇到文章结尾
- }
- cout << endl;
- }
- void initart(ifstream &_fin)
- {
- char ch;
- for(int i = 0; i < MAX_ROW; i++)
- {
- for(int j = 0; j < MAX_COL; j++)
- {
- _fin.get(ch);
- article[i][j] = ch;
- }
- }
- }
- void statistic(char (*art)[MAX_COL], char *ch)
- {
- for(int k = 0; k < MAX_CHARS_NUM; k++)
- {
- for (int i = 0; i < MAX_ROW; i++)
- {
- for (int j = 0; j < MAX_COL; j++)
- {
- if(art[i][j] == ch[k])
- frequence[k]++;
- if(art[i][j] == '*')break;//遇到文章结尾
- }
- if(art[i][j] == '*')break;//遇到文章结尾
- }
- }
- }
- /*void main()
- {
- ifstream fin("data.dat");
- char ch;
- while (fin.get(ch))
- {
- cout << ch;
- }
- fin.close();
- }*/
- void main()
- {
- ifstream fin;
- fin.open("initdata.dat");
- initchars(fin);
- cout << "The Standard Character Set: " << endl;
- show(chars);
- fin.close();
- ifstream _fin;
- _fin.open("data.dat");
- initart(_fin);
- cout << "The article is : " << endl;
- show(article);
- statistic(article,chars);
- cout << "The frequence is: " << endl;
- show(chars,frequence);
- }
字符统计(HuffmanCode的辅助代码)
最新推荐文章于 2021-05-31 16:05:53 发布