【发布时间】:2021-03-24 12:50:28
【问题描述】:
当我将数据从 txt 文件读取到链表队列程序(main.cpp、queue.cpp、queue.h)时,我遇到了问题。所以我尝试了两种方法,但都不能正常工作。 在 txt 文件中,我得到了一些行,例如四行。首先,我们从文件中读取数据,然后在 switch 循环中调用 display() 函数。
行中的第一个数字是我们将在 display() 中调用数据的数字。
例子:
1 B 14 15.68
2 B 3 23.54
1 S 5 13.2
3 B 4 9.99
Firstable 我试过了,但是使用 eof() 会出现问题,当它读取最后一行两次时:
while (!input.eof()) {
input >> temp->key >> temp->type >> temp->quantity >> temp->price;
if (temp->key == 1) {
item1.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
else if (temp->key == 2) {
item2.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
else {
item3.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
}
然后我尝试了另一种方法:
while (input >> key >> type >> quantity >> price) {
input >> temp->key >> temp->type >> temp->quantity >> temp->price;
if (temp->key == 1) {
item1.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
else if (temp->key == 2) {
item2.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
else {
item3.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
}
但它也有错误,例如当我在另一个函数中调用它时没有显示第一行:
main.cpp
if (option == 1) {
item1.display();
}
else if (option == 2) {
item2.display();
}
else if (option == 3) {
item3.display();
}
队列.cpp
while (ptr != NULL) {
if (ptr->key == 1) {
//cout << key << type << quantity ....
cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
ptr = ptr->next;
}
else if (ptr->key == 2) {
cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
ptr = ptr->next;
}
else if (ptr->key == 3) {
cout << ptr->key << " " << ptr->type << " " << ptr->quantity << " " << ptr->price << endl;
ptr = ptr->next;
}
}
【问题讨论】:
-
这是重新实现队列的学术练习吗?这里有很多指针。
-
"但它也有错误,比如当我在另一个函数中调用它时没有显示第一行" 你是否意识到,在你的第二次尝试中,你尝试背靠背阅读两次,而忽略第一次阅读的结果?
-
@AlgirdasPreidžius 因为我告诉我我通过这种方式从 main.cpp 中的 queue.cpp 调用函数
-
@tadman 我知道;)
-
嗯,问题是您是想学习如何实现链表,还是只需要一个链表来了解其他内容?只是想知道这里应该关注什么。如果您只需要一个列表,它们已经存在,因此您可以跳过该部分。如果您想了解如何实现一个,您需要向我们展示您的更多代码。
标签: c++ file linked-list queue