问题
I know this has something to do with eof, but I don't know how streams work exactly, i'd understand better if someone could tell me whats going on.
say I have 3 numbers {1, 2, 3} the load function puts the variables into the nodes, but when I go to print all the nodes only 1 will print.
void load() {
ifstream fload;
node *n = new node;
node *temp = new node;
fload.open("DoubleList.dat");
if (fload) {
fload >> n->data;
n->next = NULL;
n->prev = NULL;
head = n;
tail = n;
curr = n;
while (!fload.eof()) {
fload >> temp->data;
temp->next = NULL;
temp->prev = curr;
curr = temp;
tail = temp;
}
}
}
回答1:
You are allocating only 2 node
s. If the file has less than 2 values, you leak memory. If the file has more than 2 values, you are not allocating a new node
for every value.
Don't rely on eof()
, either. Let operator>>
tell you if it successfully read a value or not.
Try something more like this instead:
void load() {
// TODO: make sure the list is freed and head/tail are null before continuing!
ifstream fload;
fload.open("DoubleList.dat");
node **n = &head;
T data; // <-- use whatever your actual node data type is...
while (fload >> data) {
*n = new node;
(*n)->data = data;
(*n)->next = NULL;
(*n)->prev = tail;
tail = *n;
n = &(tail->next);
}
}
回答2:
#include <fstream>
using namespace std;
struct node
{
node *next;
node *prev;
double data;
node(node *next, node *prev, double data) // give node a constructor to not
: next{ next }, prev{ prev }, data{ data } // clutter code with assignments
{}
};
// assuming load is some member function of a list that has a head and a tail
void load() {
ifstream fload{ "DoubleList.dat" }; // use constructor to open file
if (!fload.is_open())
return; // early exit if file could not be opened
node *root = nullptr;
node *curr = root;
double value;
while (fload >> value) // as long as doubles can be successfully extracted
{
if (!root) { // if our list doesn't have a root yet
curr = root = new node(nullptr, nullptr, value);
head = tail = curr;
continue;
}
curr->next = new node(nullptr, curr, value); // construct the next node
tail = curr = curr->next; // and make it the current one.
}
}
来源:https://stackoverflow.com/questions/52527161/why-is-this-load-function-only-grabbing-the-first-thing-in-the-file