我正在编写一个程序,让用户通过读取文本文件插入AVL树,然后按顺序遍历输出到另一个文本文件,这是我的程序:
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);
}下面是输入文件的示例:
9 20 60 10 30 90 42当我运行上面的程序时,输出文件只有一个编号:
20如果我将它打印到控制台屏幕,而不是打印到文件中,这是正确的:
9 10 20 30 42 60 90我不知道为什么当我将它打印到控制台屏幕时,它是正确的,但是当我输出到文件时,它只有一个数字。有人能帮我吗?谢谢你的帮忙!
发布于 2021-07-09 06:32:01
你应该使用std::ofstream ofs ("output.txt", std::ofstream::app);
如果不添加模式参数(它使用std::ofstream::out默认值),则将数据打印到文件的开头。
并且不要忘记在完成输出后调用std::ofstream::close();,否则可能会丢失缓冲区中的数据。
也许有更好的方法:
void in_order(std::ofstream& ofs, AVLTree* root)
{
...
}
int main ()
{
...
std::ofstream ofs ("test.txt");
in_order(ofs, root);
ofs.close();
}https://stackoverflow.com/questions/68311975
复制相似问题