首页 > 解决方案 > 从文本文件中读取并存储在链表 C++ 中

问题描述

一周后,我用 C++ 编写了一个实现字典程序的代码。它从我的“dictionary.txt”文件中读取并将其存储在链表中

我的链表节点是:

struct node {
    string data;
    string m;
    int mcount ;
    struct node *link; 
};

Search() 函数是

int search ( char *str )
{
    struct node *head = NULL ;
    node *newnode;
    string word = str;
    node *p;
    newnode = new node();
    char temp1 [ 20 ] ;
    char temp2 [ 20 ] ;
    int i ;
    ifstream n;

    //n = dic [ toupper ( str [ 0 ] ) - 65 ] ;
    n.open("dictionary.txt", ios::out);
    if(n.fail()){
        
        cout<<"\nFile not found!";
        exit(0);
    }
    strcpy ( temp2, str ) ;
    strupr ( temp2 ) ;
    head = newnode;
    while ( !n.eof() )
    {   
        getline(n, newnode->data , ' ');
        newnode->link = new node();
        newnode = newnode->link;
   }
        p = head;
        p->link=newnode;
        node *tempnode;
        tempnode = head;
        while(tempnode!=NULL){
        cout<< tempnode->data;
        tempnode = tempnode->link;
        }

我希望它像这样工作:如果我想在 dictionary.txt 文件中搜索一个单词,它应该从 dictionary.txt 文件中获取它的含义。但它并没有根据我的输入获取数据,它只是每次都得到相同的输出。简而言之,它不是根据我的输入进行搜索。

我在“dictionary.txt”中存储了此类单词的含义

alive living
again repeat
against opposite
ant name of insect

它应该根据第一个单词进行搜索,直到遇到空格或某些特殊字符。

主要的()

int main() {
string word;
int i;
 cout<< "\nEnter the word to search : " ;
                fflush ( stdin );
                gets ( word ) ;
                i = search ( word ) ;
                if ( ! i )
                    cout<< "Word does not exists." ;
return 0;
}

是我遗漏了什么还是错误是什么?我已经阅读了太多文章,但有很多很少或没有回复符合我的问题。

标签: c++linked-listfile-handling

解决方案


推荐阅读