Почему эта функция загрузки только захватывает первое в файле? - PullRequest
0 голосов
/ 27 сентября 2018

Я знаю, что это как-то связано с eof, но я не знаю, как именно работают потоки, я бы лучше понял, если бы кто-то мог сказать мне, что происходит.

скажем, у меня есть 3 числа {1, 2, 3} функция загрузки помещает переменные в узлы, но когда я иду на печать, все узлы будут печататься только 1.

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;

        }
    }
}

Ответы [ 2 ]

0 голосов
/ 27 сентября 2018

Вы выделяете только 2 node с.Если файл имеет менее 2 значений, вы теряете память.Если файл имеет более 2 значений, вы не выделяете новое node для каждого значения.

Также не полагайтесь на eof().Пусть operator>> скажет вам, успешно ли оно прочитало значение.

Вместо этого попробуйте что-то вроде этого:

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);
    }
}
0 голосов
/ 27 сентября 2018
#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.
    }
}
...