read txt file into a sorted linked list c++

2019-09-02 16:47发布

问题:

just started to learn about linked list and have to make a OOP to read, sort, and display some file.

Here's the format of the txt file:

20  
john  
adam  
george  
.  
.  
.  

the first number is the number of names included in the txt file and each line follows has a name.

Here's my main.cpp

#include "ListClass.h"
#include <iostream>
#include <fstream>
#include <string>


using namespace std;


int main()
{
//declaring class
ListClass name;
string file;
    char holder[256];

cout<<"Please enter the data file to be read: "<<endl;
cin>>file;

//input the data file
ifstream myIn;
myIn.open(file.c_str());

//reading each line and perform functions
    myIn>>number;
    myIn.ignore(256,'\n');

while(myIn.peek()!=EOF)
{
           myIn.getline(holder, 256, '\n');
           nameRec.name=holder;

    readFile(nameRec.name);
            display();

}

myIn.close();

    return 0;
}

and here's the .h file:

#include <string>
using namespace std;

#ifndef LISTCLASS_H
#define LISTCLASS_H

    struct record
{
    // name
    string name;
};
typedef record nameRec;

struct node
{
    nameRec data;
    node* next;
};
typedef node nodeType;
typedef node* nodeTypePtr;


class ListClass
{
public:

    ListClass();
    ListClass(const ListClass&L);
    ~ListClass();

    void readFile();
    void insert();
    void display();
    void search();
    void checkList();
    int listLength();

private:

    int number=0;

    nodeTypePtr head;

};
#endif

and my implementation .cpp

 #include "ListClass.h"

using namespace std;

//default constructor
ListClass::ListClass()
{
head=NULL;
}

ListClass::ListClass(const Class& L)
{
if(L.head==NULL)
    head=NULL;
else
{
    head=new node;
    assert(head!=NULL)
    head->item=L.head->item;
}
void ListClass::readFile(nameRec.name)
{
   nodeTypePtr prev, curr;
   nodeTypePtr newNode;
   newNode= new node;
   assert(newNode);
   newNode->nameRec.name;

   prev=head;
   curr=head;

   while ((curr!=NULL)&&(curr->cityRec.name))
 {
     prev= curr;
     curr= curr->next;
 }
   if (curr==head)
 {
     newNode->next=head;
     head=newNode;
 }
  else
 {
     newNode->next=curr;
     prev->next=newNode;
 }

void sortedListClass::display()
{
for (nodePtrType cur=head; cur!=NULL;cur=cur->next)
    cout<<cur->data.name<<endl;
}

I'm fairly new to programming so I could be doing this wrong. I'd just like to know how to read a file into a linked list preferably into a sorted linked list and then display it.