1 Replies - 396 Views - Last Post: 06 October 2012 - 07:18 PM Rate Topic: -----

#1 Planet Telex  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 15-November 10

Reading from an input file to a linked-list

Posted 06 October 2012 - 06:34 PM

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class ReadToLinkedList
{
private:
	struct node
	{
		string data;
		node *next;
	};
public:
	void ReadFromFile(ifstream& inFile, ofstream& outFile)
	{
		string value;
		string number;
		node *head;
		node *temp1;
		node *temp2;
		bool first;

		head = NULL;
		temp1 = NULL;
		first = false;

		if(inFile.is_open())
		{
			while(!inFile.eof())
			{
				getline(inFile,number);
				temp1->data = number;
				temp1->next = head;
				head = temp1;
				node *temp1 = new node;
			}
		}
		cout << temp1->data; //CRASHES HERE


	};
};

int main()
{
	ReadToLinkedList you;
	ifstream inFile("INPUT.txt");
	ofstream outFile("OUTPUT.txt");
	you.ReadFromFile(inFile, outFile);
	system("PAUSE");
	return 0;
}


I crash when I try to output temp->data. Why?

View PostPlanet Telex, on 06 October 2012 - 06:33 PM, said:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class ReadToLinkedList
{
private:
	struct node
	{
		string data;
		node *next;
	};
public:
	void ReadFromFile(ifstream& inFile, ofstream& outFile)
	{
		string value;
		string number;
		node *head;
		node *temp1;
		node *temp2;
		bool first;

		head = NULL;
		temp1 = NULL;
		first = false;

		if(inFile.is_open())
		{
			while(!inFile.eof())
			{
				getline(inFile,number);
				temp1->data = number;
				temp1->next = head;
				head = temp1;
				node *temp1 = new node;
			}
		}
		cout << temp1->data; //CRASHES HERE


	};
};

int main()
{
	ReadToLinkedList you;
	ifstream inFile("INPUT.txt");
	ofstream outFile("OUTPUT.txt");
	you.ReadFromFile(inFile, outFile);
	system("PAUSE");
	return 0;
}


I crash when I try to output temp->data. Why?

What's the proper way to read from an input file?

Is This A Good Question/Topic? 0
  • +

Replies To: Reading from an input file to a linked-list

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3489
  • View blog
  • Posts: 10,748
  • Joined: 05-May 12

Re: Reading from an input file to a linked-list

Posted 06 October 2012 - 07:18 PM

That is probably because temp1 is null from line 25, and you failed to open your file, so it goes to line 36 and you try do dereference a null pointer.

You have other issues:
- You are using inFile.eof(), but the EOF bit is only set after a file operation causes the stream to detect the end of the file.
- You define another temp1 variable within the scope of lines 31-37. You probably just want to use the temp1 from the outer scope and move the allocation to right after the getline().
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1