字符串没有被定向到输出文件C++

问题描述

所以我试图将从函数获得的字符串定向到输出文件。发生的事情是 buildTree 函数正在创建一个向量字符串的二叉树,然后在它完成后,它调用 printInorder 函数来按顺序打印该函数。如果我替换 file data); 它将正确打印出树。与 cout data);但是尝试从 tree.printVector() 引导返回的字符串似乎没有任何作用。运行后file.txt还是空白。感谢您的帮助

这是代码

#include <iostream>
#include "node.h"
#include "tree.h"
#include "cleanString.h"
#include <string>
#include <fstream>
using std::cout;
using std::endl;

BST tree,*root = nullptr;

void buildTree(std::string name){
    ifstream file;
    file.open(name);
    
    if (file){
        std::string word;
        file >> word;
        word = cleanString(word);

        root = tree.Insert(root,word);

        while (file >> word){
            word = cleanString(word);
            tree.Insert(root,word);
        }

        //tree.Inorder(root);
        printInorder(root);
    } else{
        cout << "not a file" << endl;
    }
    file.close();
}

void printInorder(BST* tempRoot){
    ofstream file;
    std::string vecStrings;
    file.open("file.txt");

    if (!tempRoot) { 
        return; 
    } 
    printInorder(tempRoot->left); 
    vecStrings = tree.printVector(tempRoot->data);
    file << vecStrings << endl;                    // the issue here: wont put string in file.txt
    cout << vecStrings << endl;                    // but this will print

    printInorder(tempRoot->right); 
    
    file.close();
}
void printPreorder(){

}
void printpostorder(){

}

解决方法

与其说是打开和关闭文件的方法,不如写:

std::ostream &operator

然后你就有了一个可以发送到任何输出流的通用打印方法。