首页 > 解决方案 > 从文本文件中读取并制作字典文本文件

问题描述

我想读取一个文本文件并将新单词存储在链表中。从这个链表中,我想用新词编写一个字典文件。我不知道为什么我的代码不运行。谁能帮我?

p/s:当我运行调试时,它在将向量元素存储到 new_node->word 时发现了这个 错误 这是我的代码


#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstring>

using namespace std;
typedef struct dictionary
{   string word;
    int line;
    int page;
    struct dictionary* next;
} node;


int main()
{
    node* Head = NULL;
    ifstream file("filetest.txt");
    if(file.fail())
        cout << "Loi mo file! "<<endl;
    string temp;
    int cpage = 1,cline = 1;
    while(getline(file,temp))
    {
        stringstream spliter;
        spliter << temp;
        vector<string> result;
        while(!spliter.eof())
        {
            string str;
            spliter >> str;
            result.push_back(str);
        }
        for(size_t i = 0;i != result.size();i++)
        {
            if(Find(Head,result[i])==0)
            {
                Append(&Head,result[i],cline,cpage);
            }

        }
        cline++;
        if(cline == 25)
            cpage++;

    }
    file.close();
    ;
    ofstream outfile("test.txt");
    node* p = Head;
    while(p != NULL)
    {
        outfile << p->word <<","<<p->page<<"-"<<p->line<<endl;
        p=p->next;
    }


}

追加(将成员添加到链表)

void Append(node** First,string &newstr,int newl,int newp)
{
    node* new_node = (node*)malloc(sizeof(node));
    node* last = *First;
    new_node->word=newstr;
    new_node->line=newl;
    new_node->page=newp;
    new_node->next = 0;
    if(*First == 0)
    {
        *First = new_node;
        return;
    }
    while(last->next != 0)
    {
        last = last->next;
    }
    last->next = new_node;
    return;
}

查找(检查一个单词是否是新的)

int Find(node* head,string &tumoi)
{
    node* current = head;
    while(current != 0)
    {
        if(current->word == tumoi)
            return 1;
        current = current->next;
    }
    return 0;
}

标签: c++linked-list

解决方案


您不应该malloc与 C++ 类型一起使用。它没有正确初始化它们。

您的node结构包含一个std::string需要调用其构造函数才能正确初始化的结构。

当你这样做时

    node* new_node = (node*)malloc(sizeof(node));
    new_node->word=newstr;

new_node->word初始化并且可以包含指向无处的指针。

你应该做

    node* new_node = new node();
    new_node->word=newstr;

反而。


推荐阅读