微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决字符串没有被定向到输出文件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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。