2

問題は、初めてデータ ストリームをデコードできることですが、それが無限ループになり、同じ値が何度も表示されることです... 私は 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();
}
4

1 に答える 1

2

コードには少なくとも 2 つの主要なバグがあります。

コード[]配列はほとんど初期化されていません。後で最大26程度のインデックスの配列にアクセスしても、3つの数値でしか読み取れません。

strncpy() の呼び出しは、strncpy() が最大文字数をコピーするときに文字列を null で終了しないという意味で壊れています。つまり、final を 1 に設定して strncpy() を呼び出すと、strncpy() は 1 文字をコピーし、終端の NUL 文字を追加しないため、atoi() が失敗します。

また、ハフマン コーディングで "0" と "1" の文字を使用している場合、数値 "01" と "1" は両方とも atoi() によって 1 (1) として解釈されるため、いずれにしても機能しません。異なるコードです。これが本当にハフマン コーディングである場合は、atoi() と整数を使用するべきではなく、バイナリまたは文字列だけを使用する必要があります。

ハフマン デコーディングは、ツリー データ構造を使用することでより適切に実行できます。参考のために、アルゴリズムに関する標準的な本を調べてください。

于 2012-04-26T06:38:39.133 に答える