One of my lab assignments at university is to read names from a *.txt file into a linked list of structures, and then pass the list to a function which prints the names to screen. The issue seems to be where I have assigned the value of the pointers and passing it to my function. I would appreciate if anyone could point out where I'm going wrong.
person.h:
#ifndef PERSON_H
#define PERSON_H
#include<string>
#include<fstream>
#include<iostream>
using namespace std;
struct Person
{
Person *next;
string name;
};
void walklist(Person *head_Ptr);
#endif PERSON_H
person.cpp:
#include "person.h"
void walklist(Person*head_Ptr)
{
Person *cur;
for (cur = head_Ptr; cur!=NULL; cur=cur->next)
{
cout<< cur->name<<endl;
}
}
main.cpp
#include<string>
#include<fstream>
#include<iostream>
#include"person.h"
using namespace std;
int main()
{
string myfilename, names_in;
cout<<"Please enter the name of the file to open";
cin>>myfilename;
fstream infile;
infile.open(myfilename.c_str());
if(infile.bad())
{
cerr<<"There has been a problem opening the file"<<endl;
system("PAUSE");
return -1;
}
Person *head_Ptr = NULL, *last_Ptr = NULL, *temp_Ptr;
while(infile.good())
{
getline(infile, names_in);
temp_Ptr = new Person;
temp_Ptr->name = names_in;
temp_Ptr->next = head_Ptr;
if(last_Ptr != NULL)
{
last_Ptr->next = temp_Ptr;
}
if(head_Ptr==NULL)
{
head_Ptr = last_Ptr;
}
}
walklist(head_Ptr);
system("Pause");
return 0;
}