c++ - 我将如何从二叉树写入 txt 文件?

标签 c++ object output binary-tree

我正在尝试将二叉树中的信息写入 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/

相关文章:

python - 如何使用 Python 从 URL 读取 CSV 文件?

android - 来自 Android JNI 中任何线程的 FindClass

c++ - 如何知道用于实现标准代码(例如 C++ STL)的确切数据结构和算法?

c++ - include <Eigen/Dense> 成功, include <Eigen> 失败

javascript - 动态创建嵌套 json 对象

c - 如何修复我的 e^x 近似 C 程序?

c++ - 如何使用类模板完全特化函数模板?

C++ 对象表示

html - 去除嵌入式网页的边距