如何将文件中的数字插入链接列表

时间:2015-03-22 02:51:38

标签: c++ file linked-list

我有这个程序,我试图获取一个txt文件,但是链接列表中的文件中的数字列表。该文件如下所示:

test.txt

100
200
2
94 

但是当我运行程序而不是将所有数字放入链接列表时,它只插入最后一个94的数字,请帮助

的main.cpp

#include "list.h"
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
int readFile()
 {
    int file;
    ifstream fin;
    string fn;
    cout<<"enter the name of a file "<<endl;
    cin>>fn;
    fin.open(fn.c_str());
    assert (fin.is_open());
 //reads integer data from a file and prints the data
  while (true)
  {
    fin>>file;
    if (fin.eof())
    {

       break;
    }

  }
         //cout<<data<<endl;
         return file;
 }

int main()
{
list mylist; 
mylist.insertElement(readFile());
}

list.cpp

#include "list.h"

list::list()
{
 head=NULL;
}

void list::insertElement(int element)
  {
    node *temp, *curr, *prev;
    temp = new node;
    temp->item = element;
    numberofelements++; 

   for(prev = NULL, curr = head/*value set*/; (curr !=NULL)&&
   (temp->item>curr ->item)/*condition*/; 
   prev = curr, curr = curr->next/*loop expression*/);

    if (prev == NULL)
     {
    temp-> next = head;
    head = temp;
    }
    else
    {
    temp -> next = curr;
    prev -> next = temp;
    }
  }//end of function

list.h

#include<cassert>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;    
struct node
{
  int item;
  node *next;
};
class list
{
  public:
  list();
  void insertElement(int element);

   private:
   node *head;
};

1 个答案:

答案 0 :(得分:0)

您可以在readFile功能中插入数字。

#include "list.h"
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
bool readFile(list&li)
{
    int file;
    ifstream fin;
    string fn;
    cout<<"enter the name of a file "<<endl;
    cin>>fn;
    fin.open(fn.c_str());
    assert (fin.is_open());
    //reads integer data from a file and prints the data
    while (cin>>file)
    {
        li.insertElement(file);
    }
    //cout<<data<<endl;
    if (cin.bad())
        return false;
    return true;
}

int main()
{
    list mylist; 
    readFile(mylist);
}