当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - writing binary tree in a txt file preorderly

问题描述:

I have a function that writes things from a binary tree. When I run it, it just writes the root of the tree in the txt. can someone tell me what is wrong here?

void tree::wrte(person *p)

{

ofstream out("myfile.txt");

struct register{

char ID[15];

char name[30];

char surname[30];

};

register reg;

if(!(mybook=fopen("myfile.txt","a+")))

{

if (!(mybook=fopen("myfile.txt","w+")))

{

cerr<<"Couldnt opened"<<endl;return;

}

}

if(p)

{

strcpy(reg.name,p->name);

strcpy(reg.ID,p->ID);

strcpy(reg.surname,p->surname);

out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;

wrte(p->left);

wrte(p->right);

}

out.close();

}

网友答案:

If you really must open the file each time you call wrte(), I'd change the code to close the current stream before recursively calling write again:

if(p)
{
    ...
    out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;
    out.close();
    wrte(p->left);
    wrte(p->right);
    ...

However, a better design would be to pass an ostream to your wrte() function:

void tree::wrte(ostream& out, person *p){
    ...
    if(p)
    {
        ...
        out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;
        wrte(out, p->left);
        wrte(out, p->right);
    }
    ...
}

Then open the output stream before your first invocation of wrte():

int main()
{
    ...
    ofstream out("myfile.txt");

    ...
    tree_ptr->wrte(out, p);
    out.close();
    ...
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: