【发布时间】:2018-01-25 09:24:00
【问题描述】:
我一直在编写一组包含指向列表的指针的列表,并且想要创建一个方便的界面来浏览它们并将选定的数据从文件保存到列表。这个想法是有一个具有唯一 ID 的“API 列表”,每当我找到一个唯一 ID 时,我都会创建一个新的 API 列表。现在,我正在将数据保存到一个“API 列表”相关列表中。
结构看起来很简单:
enum day { mon, tue, wed, thu, fri, sat, sun };
static const string enumValues[] = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
struct _ListSub {
string h;
day d;
string gr;
string sub;
_ListSub *next = nullptr;
};
struct ListAPI {
string id;
ListAPI *next = nullptr;
_ListSub *head = nullptr;
};
我从文件读取值并将其保存到列表的函数如下所示:
ListAPI *createLists(string arg) {
ifstream f_in;
ListAPI *listGrip;
f_in.open(arg);
if (!f_in.is_open()) {
cout << "\"" << arg << "\": file does not exist!" << endl;
exit(EXIT_FAILURE);
}
listGrip = new ListAPI;
listGrip->head = new _ListSub;
while (true) {
// dummy data
string h;
string week = "";
string gr;
string id;
string sub;
if (!(f_in >> h >> week >> gr >> id >> sub)) {
break;
}
cout << "ID check: " << checkListID(id, listGrip) << endl;
listGrip->id = id;
listGrip->head->h = h;
listGrip->head->d = (day)enumerateDay(week);
listGrip->head->gr = gr;
listGrip->head->sub = sub;
listGrip->head ++;
listGrip->head = new _ListSub;
}
f_in.close();
return listGrip;
}
无论如何,数据是正确的,它工作正常,所以很久没有添加这部分(移动_listSub的头指针并创建这个对象的新实例):
listGrip->head ++;
listGrip->head = new _ListSub;
我从中得到的所有数据都是 id 女巫,我保存到 listGrip(我的列表 API),但是嵌套列表列表中的所有数据都消失了。
有人能告诉我我在这里用指针做错了什么吗?
主要:
int main( int argc, char **argv ) {
/* Directly parse options in order to avoid accepting abbrevations. */
string ARGUMENT;
validate_arguments;
cout << "File path: " << ARGUMENT << endl;
ListAPI *listGrip;
listGrip = createLists( ARGUMENT );
//listGrip->head;
cout << "List has been created." << endl;
cout << "ID: " << listGrip->id << endl;
cout << "Subject: " << listGrip->head->sub << endl;
cout << "Time: " << listGrip->head->h << endl;
cout << "Day: " << getTextFromEnum((short)listGrip->head->d) << endl;
delete listGrip;
return EXIT_SUCCESS;
}
【问题讨论】:
-
main()在哪里?请发布minimal reproducible example。不要描述你的代码,而是展示它。 -
"有人能告诉我我在这里用指针做错了什么吗?"一切。您只能使用指向数组的指针进行指针运算,
head不能。此外,head = new ...丢弃了您辛辛苦苦构建的旧head。 -
我建议你在一张纸上画一个3个元素的链表,然后在头指针上放置一个marker,通过移动marker并根据需要绘制一个新节点来模拟添加一个新元素。
-
_ListSub 标识符被保留。选择另一个名字。