我正在尝试将二叉树中的信息写入 txt 文件。它所做的只是删除 txt 文件中的记录,而不是写入任何内容。
这是我目前所知道的,但老实说我不知道。二叉树包含客户类的对象,以防它很重要。 p 也是树的根。
template <class elemType>
void bSearchTreeType<elemType>::writeFileTree(binaryTreeNode<elemType> *p) const
{
//Root=NULL;
ofstream fin;
fin.open("Customers.txt");
if (p != NULL)
{
writeFileTree(p->llink);
//cout << p->info << " ";
fin << p->info;
writeFileTree(p->rlink);
}
fin.close();
}
这是我重载的运算符。
ostream& operator >> (ostream& os, const Customer &cust)
{
//print();
os << cust.getCustNum() << endl << cust.getName() << endl;
Address address = cust.getAddress();
os << address.getStreet() << endl << address.getCity() << endl << address.getState() << endl << address.getZip() << endl;
//address.print();
return os;
}
最佳答案
每个递归调用都会打开(并且很可能会失败)磁盘上的相同 文件和一个新的文件对象。那是行不通的。您需要打开所有这些外部的文件并将其作为引用参数传递
template <class elemType>
void bSearchTreeType<elemType>::writeFileTree(std::ostream& os, binaryTreeNode<elemType> *p) const
{
if (p != NULL)
{
writeFileTree(os, p->llink);
os << p->info << '\n';
writeFileTree(os, p->rlink);
}
}
让调用者打开和关闭文件。顺便说一句,您的节点指针应该(可能)是 const
参数。
关于c++ - 我将如何从二叉树写入 txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23377728/