skarchmit
skarchmit

Reputation: 459

C++ output files

I am trying to export the contents of a tree with recursion. I am not getting anything but the last element exported.

void inOrder(tree *root) {
    out.open("output.txt");
    if (root != NULL)
    {
        inOrder (root->left);
        out << root -> item << " \t";      //This doesn't work
        cout << root -> item << " \t";       //This works
        inOrder (root->right);
    }

    out.close();
    out.clear();
}

I'm not sure where I am going wrong when exporting here.

Upvotes: 0

Views: 54

Answers (1)

vsoftco
vsoftco

Reputation: 56577

Move your

out.open("output.txt");    

and

out.close();
out.clear();

outside your function, as during the recursion you end up re-opening the file (which will cause a stream error), then closing it. In fact, you don't even need the last two of them, the destructor of the ofstream will automatically close the file when the program terminates.

Upvotes: 5

Related Questions