尝试将输出定向到文件但出现分段错误

问题描述 投票:0回答:1

做一个项目,我必须从 .txt 文件中读取葛底斯堡演说,并使用二叉搜索树作为计数方法在输出文件中按字母顺序输出单词及其词频。

我很确定使用输出文件段有一些错误,因为我以前有一个版本,我输出到终端,一切都相应地进行。

这是我当前的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct TreeNode{
    string word;
    int count = 0;
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
};

void insert(TreeNode*&, const string&);
void display(TreeNode*&, ofstream&);

int main()
{
    string word = " ";
    ifstream inputFile;
    ofstream outputFile;
    string outputFileName;
    string inputFileName;

    cout << "What is the name of the file that would like to use? ";
    cin >> inputFileName;
    inputFile.open(inputFileName);

    cout << "What is the name of the file that you want the output in? ";
    cin >> outputFileName;

    TreeNode* root;

    while( inputFile >> word )
    {

        if(!isalnum(word.back()))
        {
            word.pop_back();
        }
        if(word.length() < 3)
        {
            continue;
        }
        insert(root, word);
    }
    inputFile.close();

    outputFile.open(outputFileName);
    display(root, outputFile);

    outputFile.close();
}

void insert(TreeNode*& root, string const& leMot)
{
    if(root == nullptr)
    {
        root = new TreeNode;
        root->count++;
        root->word = leMot;
        root->left = root->right = nullptr;
    }
    else if (root->word.compare(leMot) > 0)
    {
        insert(root->left, leMot);
    }
    else if(root->word.compare(leMot) < 0)
    {
        insert(root->right, leMot);
    }
    else if (root->word == leMot)
    {
        root->count++;
    }
}

void display(TreeNode*& root, ofstream& file)
{
    if(root != nullptr)
    {
        display(root->left, file);
        file << root->word << " " << root->count << "\n";
        display(root->right, file);
    }
}

我之前只输出到终端的版本是类似的,除了我的显示函数没有将 ofstream& 作为参数,而不是在函数定义中输出“文件”,而是 cout。

在您在上面看到的当前版本中,我希望它按字母顺序列出单词,所有单词都在新文件中出现,如下所示:

  And 8 
  But 8
  ...
c++ string file-io binary-search-tree ofstream
1个回答
0
投票

原来我只需要将我的二叉树初始化为 nullptr :)

© www.soinside.com 2019 - 2024. All rights reserved.