为什么此加载功能仅抓取文件中的第一件事? [英] Why is this load function only grabbing the first thing in the file?

查看:66
本文介绍了为什么此加载功能仅抓取文件中的第一件事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

说我有3个数字{1、2、3}
加载函数将变量放入节点中,但是当我打印所有节点时,只会打印1个。

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;

        }
    }
}


推荐答案

您仅分配2个节点 s。如果文件的值小于2,则泄漏内存。如果文件具有两个以上的值,则不会为每个值分配新的节点

You are allocating only 2 nodes. 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.

也不依赖 eof()。让 operator>>> 告诉您是否成功读取了一个值。

Don't rely on eof(), either. Let operator>> tell you if it successfully read a value or not.

尝试类似的方法:

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);
    }
}

这篇关于为什么此加载功能仅抓取文件中的第一件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆