为什么此加载功能仅抓取文件中的第一件事?

时间:2018-09-26 23:04:14

标签: c++ c++11 eof

我知道这与eof有关,但是我不知道流是如何工作的,如果有人可以告诉我发生了什么,我会更好地理解。

说我有3个数字{1、2、3} load函数将变量放入节点中,但是当我打印所有节点时,只会打印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 :(得分:1)

您仅分配2个node。如果文件的值小于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);
    }
}

答案 1 :(得分:0)

#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.
    }
}