<分区>
我正在尝试将我的霍夫曼树序列化为一个文件,但对问题的递归性质有疑问。我可以使用 cout 将它打印到控制台,但是当我尝试将它存储在字符串中或写入文件时出现段错误。
string putData(Node *n, string &s) {
if (n->leaf()) {
s << "[" << n->value() << "]";
} else {
s << ".";
}
if (n->left())
putData(n->left(), s);
if (n->right())
putData(n->right(), s);
}
对于 ofstream 对象也是同样的问题。实际上,在程序出现段错误后,我检查了文件及其内容是否正确。但是为什么最后会出现段错误呢?如何阻止程序出现段错误?
string putData(Node *n, ofstream &s) {
s.open("huffout.txt", ios::app);
if (n->leaf()) {
s << "[" << n->value() << "]";
} else {
s << ".";
}
s.close()
if (n->left())
putData(n->left(), s);
if (n->right())
putData(n->right(), s);
}