c++ - 如何从文本文件加载链表?

标签 c++ loops linked-list

问候 我一直在做作业,其中我必须创建一个链表程序,该程序可以从文本文件保存和恢复其数据。我已经完成了大部分工作,但是我在使用从它创建的文本文件中的数据恢复链接列表时遇到了一些问题。当我恢复它时,最后一个元素重复两次。我相信它与循环有关,但我不确定我是否包括了我的任务的整个范围。

下面是我到目前为止编写的程序代码:

列表节点.h

#pragma once
template<class T> class List;
template<class T>

class ListNode
{
 friend class List<T>;
public:
 ListNode(const T&);
 T getData()const;
private:
 T data;
 ListNode<T>*next;
};//end ListNode class

template<class T>
ListNode<T>::ListNode( const T &info):data(info), next(NULL)
{
}//end default constructor
template<class T>
T ListNode<T>::getData()const
{
 return data;
}//end function getData 

列表.h

#pragma once
#include<iostream>
#include <fstream>
using namespace :: std;
#include "ListNode.h"
template<class T> 
class List 
{
private:
 ListNode<T> *head;
 int size;
 ListNode<T> *find(int index) const;
public:
 List();
 List(const List<T> &aList);
 ~List();
 int getLength() const;
 void insert (int index, T tempData);
 void remove(int index);
 void retrieve(int index, T &tempData);
 bool isEmpty() const;
 void print() const;
 void save();
 void restore();
};//end List class 

损坏的功能:

template <class T>
void List<T>::restore()
 {
     ifstream inFile;
     inFile.open("listFile.txt");

     T value=0;
     int index, check =0;

     cout << "Now reading the data from the text file..." << endl;
         //inFile >> value;
         //cout << "Value is : " << value << endl;


        while (inFile != NULL) 
        {
            inFile >> value;
            index = getLength();
            cout << value << endl;
            insert(index+1, value);

            inFile.close();

        } 


 } // end function restore

测试时保存到文本文件的链表数据为:

35
45
55
65

当从文本文件中恢复链表时,这是它的内容:

35
45
55
65
65

我该如何解决这个问题?

最佳答案

令我惊讶的是,您的restore 功能完全有效。但是,是的,它在重复最后一个元素。试试这个:

while(inFile >> value)
  ...

编辑:
好吧,就试这么多:

while(inFile >> value)
{
  cout << value << endl;
}

它是否正确显示值?

关于c++ - 如何从文本文件加载链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186004/

相关文章:

C - 价格查询程序

PHP MYSQL VALUE 变量

第 11 行 : Cannot read property 'oddNum' of undefined 上的 Javascript errorType 错误

c++ - 类型 'int&' 的引用初始化无效,传递参数 1 时出错

c++ - 在 C++20 获得批准之前,我应该如何处理时代以来的值?

c++ - 如何为该球体添加纹理?

java - 在 Java 中实现新的 LinkedList 方法

Python - 链表节点比较需要额外的取消引用

c++ - 创建一副纸牌

c++ - 函数参数的默认参数是否被视为该参数的初始值设定项?