我想通过跟随代码表以编程方式将存储在文件中的字符串转换为字符代码(编码)的字符串。这串二进制代码应该转到一个文件中,我可以从这个文件中将它恢复为稍后的字符串(解码)。代码表中的代码是使用霍夫曼算法生成的,代码表存储在一个文件中。给定一个自定义代码表的字符串编码
例如,通过下面的一个代码表,其中的字符和其相应的代码是单个隔开这样的:
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,但它应该是长于!
请帮忙!有什么我错过了吗? (NB我的C++代码有没有语法错误)
你是否尝试在调试器中逐句通过你的代码? –
在'codefile.txt'中找到第一个字符的编码值,写出来并且现在必须找到第二个字符的编码值之后,您认为会发生什么?你的'codefile_input'仍然在文件的中间,在某个地方,它不会奇迹般地回到文件的开头,而是单独搜索第二个字符的编码值。 –
+ Sam所以我怎样才能让codefile_input回到文件的开头? –