Hey, Im having some trouble with linked lists, I have been givin a task where I am asked to crreate a linked list which reads in a random set of chars from a .txt file and stores them in a linked list, then prints them out in a seperate function.
here is my code
#include <iostream>
#include <fstream>
using namespace std;
struct node
{
char base;
node* next;
};
void initialise(node*& head);
void read(node*& head);
void print(node*& head);
int main()
{
node* head = NULL;
cout << "Set linked list to NULL" << endl;
initialise(head);
cout << "Reading from file into linked list" << endl;
read(head);
cout << "Printing out linked list" << endl;
print(head);
return 0;
}
void initialise(node*& head)
{
head = NULL;
}
void read(node*& head)
{
node* temp;
char filename[40];
ifstream ins;
cout << "Filename: ";
cin >> filename;
ins.open(filename, ios::in);
temp = new node;
if (temp == NULL)
{
cout << "An error occured: " << endl;
exit(0);
}
if(ins.good())
{
while(!ins.eof())
{
ins >> temp->base;
temp->next = NULL;
if (head == NULL)
head = temp;
else
{
node* z;
z = head;
while (z->next != NULL)
{
z = z->next;
}
z->next=temp;
}
}
}
}
void print(node*& head)
{
node* temp;
temp = head;
while (temp != NULL)
{
cout << temp->base << endl;
temp = temp->next;
}
}
text file contains random chars, like "AINFUEH EIUDNUIEW IWEUNF" and whitespaces are ignored.
for some reason, when it prints out, it gets stuck in a loop and only prints out the last char in the text file over and over...
can someone please tell me what im doing wrong?