ska*_*mit 0 c++ io input output
我试图用递归导出树的内容.除了导出的最后一个元素,我没有得到任何东西.
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();
}
Run Code Online (Sandbox Code Playgroud)
我不确定在这里出口时我出错了.
移动你的
out.open("output.txt");
Run Code Online (Sandbox Code Playgroud)
和
out.close();
out.clear();
Run Code Online (Sandbox Code Playgroud)
在函数外部,如在递归过程中最终重新打开文件(这将导致流错误),然后关闭它.事实上,你甚至不需要最后两个,ofstream当程序终止时,will 的析构函数会自动关闭文件.