【问题标题】:Writing elements in file, reading not the same elements在文件中写入元素,读取不同的元素
【发布时间】: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


【解决方案1】:

写入二进制数据时,不能使用in &gt;&gt; xout &lt;&lt; x,因为它们是“文本读写”功能。

所以,而不是:

out<<unsigned char(c);
out<<int(n);

你需要使用:

out.write(&c, sizeof(c));
out.write(reinterpret_cast<char*>(&n), sizeof(n));

更详细的解释:

n = 12345;
out << n; 

12345 输出为单个字符。

如果你输出这个:

c = '1';
n = 2345;
out << c << n;

那么输出也将类似于12345

另一方面,in &gt;&gt; c 会跳过空格,所以

c = ' ';
n = 1234;
out << c << n;

in >> c >> n; 

输入后会有c == '1'n==234

【讨论】:

  • 我采纳了您的建议,现在效果很好!我也必须在阅读中制作演员表。谢谢你,垫子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
相关资源
最近更新 更多