【发布时间】:2019-02-11 20:13:24
【问题描述】:
我正在尝试将具有以下值的文本文件加载: 10 11 12 13 14 15 16 17 18 19 20 30 40 50 55 60 70 80 90 91 92 93 94 95 96 97 98 99 到链接列表中,插入每个新值都放入列表的末尾。我遇到的问题是,当我运行代码时,我得到一个错误,我试图通过一个需要 int 的函数运行一个字符串,这是有道理的,但是一旦我将 stoi() 添加到混合中将值转换为 int,我开始收到大量错误。
过去一天左右我一直在研究这个功能,但我的搜索都没有产生任何结果。我觉得我很接近这个,但我可能在这里遗漏了一些重要的东西。链表作为一个整体还是很新的,我们上周刚刚在课堂上了解了它们。
#include <iostream>
#include <fstream>
#include <string>
#include "linkedlist.h" // Has the prototypes for each function
using namespace std;
// I didn't include a lot of functions since I don't think they're
// related to the error, but let me know if I should
Node* createNewNode(int data) {
Node *ptr;
Node *temp = new Node();
temp -> data = data;
temp -> next = NULL;
ptr = temp;
return ptr;
}
Node* createNewList() {
Node *head = NULL;
return head;
}
Node* load(string filename) {
Node *head = createNewList();
string num;
ifstream myfile(filename.c_str());
while(myfile >> num) { // looping through each number
int num1 = stoi(num); // Converting string to int
myfile << insertAtEnd(head, num1);
}
return head;
}
void insertAtEnd(Node *list, int data) {
Node *ptr = createNewNode(data);
if (list == NULL) {
list = ptr;
}
else {
Node *temp = list;
while(temp -> next != NULL) {
temp = temp -> next;
}
temp -> next = ptr;
}
}
int main() {
load("../resource/listdata.txt"); // name/location of the file
//No errors from rest of code but I can post if necessary
}
错误太多了,我无法将它们粘贴在这里,但我在这里截取了大部分错误:https://i.imgur.com/GtXZ5oy.png。
提前感谢您能给我的任何帮助!
编辑:
Node* load(string filename) {
Node *head = createNewList();
string num;
ifstream myfile(filename.c_str());
while(myfile >> num) { // looping through each number
int num1 = stoi(num); // Converting string to int
insertAtEnd(head, num1);
}
myfile.close();
return head;
}
不再有任何编译错误,但在代码运行时会输出:
0
0
NULL
exit status -1
如果我不得不猜测,我会假设我现在的问题是while(myfile >> num) 区域,因为我认为代码没有正确遍历文本文件并使用数字,尽管我不确定。
编辑 2:
Node *load (string filename) {
Node *head;
string num;
ifstream myfile(filename.c_str());
while(myfile >> num) {
if(head) {
int num1 = stoi(num);
insertAtEnd(head, num1);
}
else {
head = createNewList();
int num1 = stoi(num);
head = createNewNode(num1);
}
}
myfile.close();
return head;
}
我希望我正确地按照说明进行操作,尽管我很有可能没有...因为我很想看看现在什么不起作用。
【问题讨论】:
-
first 错误消息通常是最重要的。在那之后,错误消息可能是由于编译器试图通过引入一些结果无法正常工作的东西来从第一个消息中恢复而导致的。因此,请发布 first 错误消息,以及与之相关的任何标记为“note”的内容。
-
你为什么 A) 曾经使用链表而不是
std::vector? B) 实现您的自己的 列表,而不是仅仅使用std::list(但真的,已经使用std::vector)?链表是一种可怕的数据结构,用于暴露现代 CPU/内存子系统。 -
insertAtEnd返回void。>>将尝试存储数据的正是这个void。与your Rubber Duck 讨论这是否是个好主意。 -
@thb 缓存一致性问题很难 - 不会咬那个。 ;)
-
@thb 感谢您继续尝试提供帮助!你的评论让我想起了我写的东西,是的,那部分没有意义。我在
insertAtEnd()之前删除了myfile >>,这消除了我遇到的所有错误。然而,这样做的结果是它给了我这个输出:'0 0 NULL exit status -1'。我不完全确定那里发生了什么,并且它没有给我任何其他错误......我将编辑我的主要帖子以显示我所做的更改,这些应该会在一分钟内完成。跨度>
标签: c++ struct linked-list text-files