#include "HuffmanTree.h"
#include <iostream>
#include <vector>
#include<string>
using namespace std;
bool IncludeChinese(string& str);
int main()
{
string s;
// 检查是否包含中文
do {
cout << "请输入一段不包含中文的字符串,以#结尾" << endl;
getline(cin, s, '#');
} while (IncludeChinese(s));
//根据统计表生成哈夫曼树
HuffmanTree tree(s);
//计算哈夫曼编码
tree.GetHuffmanCode();
//展示哈夫曼编码表
cout << endl << endl << "由以上内容生成如下的哈夫曼编码表" << endl;
tree.displayTable();
cout << endl << endl;
//对字符串s进行哈夫曼编码
cout << endl << endl << "经哈夫曼编码后的密文为:" << endl;
tree.encode(s);
cout << endl << endl;
//解码
string code;
cout << "请输入待解码的Huffman密文" << endl;
cin >> code;
cout << endl << endl << "经哈夫曼解码后的明文为:" << endl;
tree.decode(code);
return 0;
}
bool IncludeChinese(string& str)
{
int i = 0;
while (1)
{
if (str.c_str()[i] == 0)
break; //如果到字符串尾则说明该字符串没有中文字符
//0x80=1000 0000(二进制)
if (str.c_str()[i++] & 0x80) //如果字符高位为1且下一字符高位也是1则有中文字符
if (str.c_str()[i] & 0x80)
{
cout << "\n您输入的字符串中含有中文,";
return 1;
}
}
return 0;
}