c++ - 从文本文件中读取并制作字典文本文件
问题描述
我想读取一个文本文件并将新单词存储在链表中。从这个链表中,我想用新词编写一个字典文件。我不知道为什么我的代码不运行。谁能帮我?
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;
}
解决方案
您不应该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;
反而。
推荐阅读
- c# - 使用具有未指定类型参数的泛型作为字典中的值
- talend - Talend - 从 tLogRow/tSort 中提取文件名
- javascript - 如何播放音频javascript
- javascript - 在javascript中同步读取本地文本文件
- php - 面临 PHP 5.6 到 7.x 版本的代码问题
- jquery - 使用 AJAX 源将 JSON 数据加载到 JQuery DataTables
- java - 使用某些字体时 iReport 崩溃
- php - 如何在作曲家中更改代理
- angular - src/app/app.module.ts(23,3) 中的错误:错误 TS1146:预期声明
- php - 如何在 Symfony 4 中找到 app/AppKernel.php?