简体   繁体   中英

Read from text file and make a dictionary text file

I want to read a text file and store new words in linked list. From this linked list I want to write a dictionary file with new words. I don't know why my code don't run. Can anyone help me?

p/s: when i run debug it found this when store vector element to new_node->word Error This is my code


#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;
    }


}

Append( add member to linked list)

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;
}

Find( check if a word is new or not)

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

You should not use malloc with C++ types. It does not properly initialize them.

Your node struct contains a std::string which needs to have its constructor called to be properly initialized.

When you do this

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

The new_node->word is not initialized and can contain pointers to nowhere.

You should do

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

instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM