【发布时间】:2016-11-14 13:57:49
【问题描述】:
我想通过遵循代码表以编程方式将存储在文件中的字符串转换为字符串(编码)。然后二进制代码字符串应该转到一个文件,我可以稍后将其恢复为字符串(解码)。代码表中的代码是使用霍夫曼算法生成的,代码表存储在一个文件中。
例如,通过以下代码表,其中字符及其对应的代码是单行距的,如下所示:
E 110
H 001
L 11
O 111
编码“HELLO”应输出为“0011101111111”
我的 C++ 代码似乎无法完成编码字符串。这是我的代码:
int main
{
string English;
ifstream infile("English.txt");
if (!infile.is_open())
{
cout << "Cannot open file.\n";
exit(1);
}
while (!infile.eof())
{
getline (infile,English);
}
infile.close();
cout<<endl;
cout<<"This is the text in the file:"<<endl<<endl;
cout<<English<<endl<<endl;
ofstream codefile("codefile.txt");
ofstream outfile ("compressed.txt");
ifstream codefile_input("codefile.txt");
char ch;
string st;
for (int i=0; i<English.length();)
{
while(!codefile_input.eof())
{
codefile_input >> ch >> st;
if (English[i] == ch)
{
outfile<<st;
cout<<st;
i++;
}
}
}
return 0;
}
对于“The_Quick_brown_fox_jumps_over_the_lazy_dog”的输入字符串,输出字符串是011100110,但应该比那个长!
请帮忙!有什么我错过的吗? (n.b. 我的 C++ 代码没有语法错误)
【问题讨论】:
-
您是否尝试在调试器中单步执行您的代码?
-
在
codefile.txt中找到第一个字符的编码值后,你认为会发生什么,写出来,现在你必须找到第二个字符的编码值?你的codefile_input仍然在文件中间的某个地方,它不会神奇地回到文件的开头,单独搜索第二个字符的编码值。 -
+Sam 那么如何让 codefile_input 回到文件的开头?
-
@RabbaniRasha 你不需要。有更优雅的解决方案。详情看我的回答。
-
如果您希望能够解码文件,您最好选择另一种编码。如果
L是11而O是111,那么111111是什么?你需要一个叫做“前缀代码”的东西。
标签: c++ string file-io huffman-code