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?

Looks to me like no new nodes are created in this loop:

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;
			}
		}

You are just continually putting a new value into temp->base and overwriting the old value. As for the infinite loop, I haven't tested it out, but I'm guessing that temp == temp->next and possibly head == temp. You need to create a new node every time you read a new value from the input file.

commented: the OP said: "+rep", so I thought I'd make it happen :) +8

You are just continually putting a new value into temp->base and overwriting the old value.

haha thank you very much, that was exactly my problem, I originally had it reading from cin, and forgot to move my new node line into the eof loop, works perfectly now :)

+rep :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.