I'm writing a program that let the user insert an AVL Tree by reading from a text file then I output it in in-order traversal to another text file, this is my program:
void in_order(AVLTree* root)
{
ofstream printToFile("output.txt");
if (root == NULL)
return;
in_order(root->left);
printToFile << root->data << " ";
in_order(root->right);
}
int main()
{
AVLTree* root = NULL;
ifstream readFromFile("input.txt");
int node;
while (!readFromFile.eof())
{
readFromFile >> node;
root = insert(root, node);
}
in_order(root);
}
Here is the sample of the input file:
9 20 60 10 30 90 42
When I run the above program, the output file only has 1 number:
20
If I print it to the console screen instead of printing to a file, it's correct:
9 10 20 30 42 60 90
I don't know why when I print it to the console screen it's correct, but when I output to the file it only has 1 number. Can anyone help me with this? Thanks for your help!
The problem with your code may be due to the fact that in recursion you re-create ofstream printToFile("output.txt");
. ofstream
buffers the output, and clears it (ie outputs to a file) at the destructor which happens not in the order as you output in a file
The solution to this problem can be to create this variable as a static variable, or to pass the stream as an argument or force to output the contents of the buffer to a file using flush
(but not sure if this will help).
So it would looks like this
// static stream
void static_in_order(AVLTree* root)
{
static ofstream printToFile("output.txt");
if (root == NULL)
return;
in_order(root->left);
printToFile << root->data << " ";
in_order(root->right);
}
//stream as argument
void arg_in_order(AVLTree* root, ofstream &printToFile)
{
if (root == NULL)
return;
in_order(root->left, printToFile);
printToFile << root->data << " ";
in_order(root->right, printToFile);
}
int main()
{
//static solution
static_in_order(root);
//arg solution
ofstream printToFile("file.txt");
arg_in_order(root, printToFile);
}
You should use std::ofstream ofs ("output.txt", std::ofstream::app);
If you don't add mode parameter it use std::ofstream::out
default, that print your data to the begin of the file.
And don't forget call std::ofstream::close();
after complete output, otherwise may lost data in buffer.
Maybe a Better way:
void in_order(std::ofstream& ofs, AVLTree* root)
{
...
}
int main ()
{
...
std::ofstream ofs ("test.txt");
in_order(ofs, root);
ofs.close();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.