Search code examples
c++ifstreamfile-writing

String is not being directed to Output file (C++)


So I'm trying to direct the String that I get from a function to an output file. What's happening is that the buildTree function is creating a binary tree of vector strings and then after it has finished, it calls the printInorder function to print the function in order. It will correctly print out the tree if I replace file << tree.printVector(tempRoot->data); with cout << tree.printVector(tempRoot->data); But trying to direct the returned string from tree.printVector() doesn't seem to do anything. The file.txt is still blank after run. Thanks for the help

here's the code

#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(){

}

Solution

  • Rather than a method that opens and closes the file, how about writing:

    std::ostream &operator<<(std::ostream &str, const BST &) { ... }

    Then you have a generic print method that you can send to any output stream.