首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将AVL树按顺序遍历输出到文件中?

如何将AVL树按顺序遍历输出到文件中?
EN

Stack Overflow用户
提问于 2021-07-09 06:03:51
回答 2查看 200关注 0票数 1

我正在编写一个程序,让用户通过读取文本文件插入AVL树,然后按顺序遍历输出到另一个文本文件,这是我的程序:

代码语言:javascript
运行
复制
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);
}

下面是输入文件的示例:

代码语言:javascript
运行
复制
9 20 60 10 30 90 42

当我运行上面的程序时,输出文件只有一个编号:

代码语言:javascript
运行
复制
20

如果我将它打印到控制台屏幕,而不是打印到文件中,这是正确的:

代码语言:javascript
运行
复制
9 10 20 30 42 60 90

我不知道为什么当我将它打印到控制台屏幕时,它是正确的,但是当我输出到文件时,它只有一个数字。有人能帮我吗?谢谢你的帮忙!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-07-09 06:31:34

代码的问题可能是因为在递归中您重新创建了ofstream printToFile("output.txt");ofstream缓冲输出,并在析构函数处清除它(即输出到文件),这与您在文件中输出的顺序不同。

解决此问题的方法可以是将此变量创建为静态变量,或者将流作为参数或强制将缓冲区的内容输出到使用flush的文件中(但不确定这是否有帮助)。

所以看起来就像这样

代码语言:javascript
运行
复制
// 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);
}
票数 0
EN

Stack Overflow用户

发布于 2021-07-09 06:32:01

你应该使用std::ofstream ofs ("output.txt", std::ofstream::app);

如果不添加模式参数(它使用std::ofstream::out默认值),则将数据打印到文件的开头。

并且不要忘记在完成输出后调用std::ofstream::close();,否则可能会丢失缓冲区中的数据。

也许有更好的方法:

代码语言:javascript
运行
复制
void in_order(std::ofstream& ofs, AVLTree* root)
{
  ...
}

int main () 
{

  ...

  std::ofstream ofs ("test.txt");

  in_order(ofs, root);

  ofs.close();


}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68311975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档