我正在编写一个程序,让用户通过读取文本文件插入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:31:34
代码的问题可能是因为在递归中您重新创建了ofstream printToFile("output.txt");。ofstream缓冲输出,并在析构函数处清除它(即输出到文件),这与您在文件中输出的顺序不同。
解决此问题的方法可以是将此变量创建为静态变量,或者将流作为参数或强制将缓冲区的内容输出到使用flush的文件中(但不确定这是否有帮助)。
所以看起来就像这样
// 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);
}发布于 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
复制相似问题