【问题标题】:huffman decoding is going nutts霍夫曼解码快疯了
【发布时间】:2012-04-26 06:26:43
【问题描述】:

问题是我第一次可以解码一个数据流,但是它会变成一个无限循环并一遍又一遍地显示相同的值……我正在使用 borland C++。解码首先将文本 a 到 z 保存在一个数组中,然后获取输入数据流,然后使用 strcpy 切割数组的内容,然后与第一个数组的内容进行比较,如果找到匹配项,则对应的 ASCII被打印。

代码:

#include<conio.h>
#include<iostream.h>
#include<string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int codes[512];
char cut_stream[100];
char input_stream[100];
char decoded_stream[256];
int test,count,cut_start,cut_end,length_of_stream,final,temp_loop_s,temp_loop_e,temp_num,comp_num,send;
void select_num(int select)
{
 int output;
 output = select + 64;
 cout << char(output);
}
void decode()
{
cout<<"\nEnter the data stream ";//<<endl;
cin >> input_stream;
length_of_stream = strlen(input_stream);
//cout<<  length_of_stream ; //only for debugging
/********************************************
              the code starts here...
********************************************/
count = length_of_stream;

//count -= count;
for(int ini =0; ini<=count ; ini++)
{
for( final=1;final<=count;final++)
{
strncpy(cut_stream, &input_stream[ini], final);
//cut_start = cut_start + 1;
/*********************************************
                          compare
*********************************************/
temp_num = atoi(cut_stream);
for(int z= 1;z<=26;z++)
{
comp_num = codes[z];
if(comp_num == temp_num)
{
send  =z;
select_num(send);
test =1;
comp_num =0;
break;
}
}

if( test ==1)
{
 test =0;
 ini = final-1; // the increment will be given on the next for loop so it is reduced here
 //final =0;
  //cout<< "im in test";

 break;

}
}

}
cout<< "end";
 while(1);
}


//cout<< decoded_stream;
//while(1);

void main()
{
cut_start =0;
cut_end = 1;
 cout <<  "Huffman decoder" <<  endl;
 cout <<  "Enter the codes for a-z" <<  endl;
 for(int i =1;i<=3;i++)
 {
 cin >> codes[i];
 }
  decode();
}

【问题讨论】:

    标签: c++ huffman-code


    【解决方案1】:

    代码中至少有两个主要错误:

    codes[] 数组大部分是未初始化的,您只能读取三个数字,即使您稍后访问该数组以获取最多 26 个左右的索引。

    对 strncpy() 的调用被中断,因为 strncpy() 在复制最大字符数时不会以空值终止字符串;也就是说,当您在 final 设置为 1 的情况下调用 strncpy() 时,strncpy() 会复制一个字符并且不附加终止 NUL 字符,这将导致 atoi() 失败。

    另外,如果您在霍夫曼编码中使用“0”和“1”字符,这将不起作用,因为数字“01”和“1”都将被 atoi() 解释为 1(一)即使它们是不同的代码。如果这真的是哈夫曼编码,你根本不应该使用 atoi() 和整数,而应该使用二进制或字符串。

    使用树数据结构更好地完成霍夫曼解码。查找任何有关算法的标准书籍以供参考。

    【讨论】:

    • 哦,我忘了,为了减少输入 26 个元素的繁琐任务,我将值减小到 3 。我可以使用 strcmp 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多