【发布时间】:2014-04-15 15:55:33
【问题描述】:
我有一个 C++ 程序,它在文件 (fstream) 上写入来自“map”的所有“键”(char) 和“值”(int)。然后我关闭了流,但是当我稍后阅读这个文件时,我注意到它打印的不是文件中的内容。 你能帮我找出问题吗?谢谢!
代码如下:
void Encoder::get_freq_tab()
{
map<unsigned char,int>::iterator it;
int next=0;
while((next = text.get()) != EOF)
{
unsigned char uc = unsigned char(next);
it=char_freq.find(uc);
if(it!=char_freq.end())
++(it->second);
else
char_freq.insert(make_pair(uc,1));
}
text.clear();
}
void Encoder::write_h_code(string s)
{
out.open(&s[0],ios::out | ios::binary);
string code;
char c;
unsigned char acc=0;
int bit,bitpos=0,cont,n;
cont=mytree.get_tree_freq();
map<unsigned char, int>::iterator it;
out<<unsigned char(char_freq.size());
cout<<"ENCODER number of chars = "<<int(char_freq.size())<<endl;
for(it=char_freq.begin();it!=char_freq.end();++it)
{
c=((*it).first);
n=(*it).second;
out<<unsigned char(c);
out<<int(n);
cout<<"ENCODER wrote "<<int(c)<<" .Size = "<<sizeof(c)<<" .Freq = "<<n<<" . Size = "<<sizeof(n)<<endl;
}
}
这部分只是关于从文件中读取字节,将频率存储在 map char_freq 中,然后写入,首先存储的 char 的数量,然后是所有的键和值。 现在是它读回这个文件的部分。
void Decoder::extract_leaves(){
unsigned char c,tot;
int n,size;
in>>(tot); // set size, per controllare il limite delle foglie
size=(tot);
cout<<endl<<"DECODER number of char = "<<size<<endl;
for(int i=0;i<size;++i)
{
in>>unsigned char(c); // reading char
in>>int(n); // reading frequence
cout<<" Decoder Val "<<int(c)<<" Freq = "<<int(n)<<endl;
}
}
当我打印和读取同一个文件时,我会看到其他频率值,例如它为 int 写入更多字节,因此某些值不会出现,因为它在读取时“跳过”它们。
【问题讨论】:
-
你的计数范围是多少?
-
在 get_freq_tab() 中,我逐字节读取,因此 unsigned char 为 0-255,我将它们存储在地图中
。 -
是的,但是每个角色有多少个?你有可能超过 255 岁吗?
-
对不起,混淆了代码位。我现在意识到问题所在了。
标签: c++ fstream huffman-code