8 Replies - 814 Views - Last Post: 22 August 2009 - 07:20 AM Rate Topic: -----

#1 UofMCreed  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

File I/O Problem

Post icon  Posted 21 August 2009 - 01:47 AM

Hi there, im having trouble with a project of mine. I am creating a program/database for storing cigar information. Specifically the brand, name and other specificts are saved individually to structs and the structs are connected via simple linked list at the moment. There is an empty text file to begin with and when the program runs you can insert as many cigars into the linked list as you want but at the end of the program I want to save the information to the file. I know how to do this normally but I seem to have some trouble because if I wish to start the program again I want it to upload the list I just created previously. The source file uses a few member functions from my class. It first uses the upload function I have which puts any data in the file into the linked list. Then the interface function which then will let you do varios things to the list such as searching, deleting, adding more, updating information etc. After completion of that function I call the final function save. I want this function to erase everything in the text file then save all the information from this linked list to the file. For some reason i cant get it to save, erase, and write properly. I would appreciate any help!!!!

The exact problem I am having is that my Upload() function isnt working and I dont know why? Code is below and class is attached.

SOURCE:
#include<iostream>
#include<string>
#include<cstddef>
#include<fstream>
#include<vector>
#include<iomanip>
#include"LinkedList.h"

using namespace std;

int main()
{
List list;
fstream inData;
ofstream outData;
string data;

inData.open("Cigars.txt");//For retrieving information from file
outData.open("Cigars.txt");//For saving to the file

list.Upload(inData);
list.Directions();
list.Interface();
list.Save(outData);

return 0;
}



HEADER/CLASS FILE
using namespace std;

struct Node
{
	string Brand;//Brand of Cigar
	string Name;//Specific name of the cigar
	double Price;//Price per stick
	double DrawRating;//Rating is 1 - 5
	double AromaRating;//Rating is 1 - 5
	double TasteRating;//Rating is 1 - 5
	double OverallRating;//Rating is the average of Draw, Aroma, and Taste
	Node *next;
};

class List
{
public:

	List();//Class Constructor
	~List();//Class Destructor
	void Delete(int x);//Deletes cigar in list
	void MakeEmpty();//Deallocates all pointers in the list 
	void Insert();//Inserts item in list
	void Save(ofstream &outData);//Writes the list to the file just before termination of program
	void Directions();
	void FunctionList();
	void Interface();
	void GetLength() const;//Returns the length of the list
	void Upload(fstream &inData);//Uploads data from file to linked list
	bool IsThere(int x);//Returns true or false is the item is in the list or not

private:

	Node *head;//Node pointer
	int length;//Variable for how long the list has become.
	vector<double> Ratings;

	double Average(vector<double> &vec);
};

List::List()//Initializes private class variables
{
	length = 0;
	head = NULL;
}

List::~List()//Deallocates pointers in the linked list(emptying the list).
{
	Node *tempPtr;

	while(head != NULL)
	{
		tempPtr = head;
		head = head->next;
		delete tempPtr;
	}
	length = 0;
}

void List::Insert()
{
/*
Pre: Nothing has yet been inserted.
Post: Cigar information has been entered successfully into the list
*/
	Node *NewPtr;//Declaring a Node pointer
	NewPtr = new Node;//Setting a pointer to a new Node created in memory

	cout << "Input Brand of Cigar -> ";
	cin  >> NewPtr->Brand;


	cout << "Input Name of Cigar -> ";
	cin  >> NewPtr->Name;

	cout << "Input Price of Cigar -> ";
	cin  >> NewPtr->Price;

	cout << "Input Draw Rating(1 - 5) -> ";
	cin  >> NewPtr->DrawRating;
	Ratings.push_back(NewPtr->DrawRating);
   
	cout << "Input Aroma Rating(1 - 5) -> ";
	cin  >> NewPtr->AromaRating;
	Ratings.push_back(NewPtr->AromaRating);

	cout << "Input Taste Rating(1 - 5) -> ";
	cin  >> NewPtr->TasteRating;
	Ratings.push_back(NewPtr->TasteRating);

	//Private member function that finds the average of the
	//ratings for the overall rating.
	NewPtr->OverallRating = Average(Ratings);

	//cout << setprecision(2) << NewPtr->OverallRating << endl;

	NewPtr->next = head;//Giving the pointer inside the node an address.
	head = NewPtr;//head now has the address of NewPtr

	length++;

	cout << "INPUTTED SUCCESSFULLY\n\n";
}

double List::Average(vector<double> &vec)
{
	double answer, total = 0;

	for(int i = 0; i < vec.size(); i++)
	{
		total = total + vec[i];
	}

	answer = total/(vec.size());

	return answer;

}

void List::GetLength()const
{
/*
Pre: 
Post: The number of nodes in the list has been given to the user
*/
	cout << "Number of Cigars in Database is: " << length << "\n\n";
}

void List::Delete(int x)
{
/*
Pre: Item in the list but not deleted
Post: Item no longer in the list because of deletion
*/
	/*
	Node *NewPtr = head;
	Node *tempPtr;
		 
	if(x == head->data)
	{
	   tempPtr = NewPtr;
	   head = head->next;
	}
	else
	{
		while(!(x == (NewPtr->next)->data))
		NewPtr = NewPtr->next;
			 
		tempPtr = NewPtr->next;
		NewPtr->next = (NewPtr->next)->next;
	}
	length--;
	delete tempPtr;
	*/
}

bool List::IsThere(int x)
{
/*
Pre: 
Post: Returns true if item is in the list. Returns false if the item is not in the list.
*/
	/*
	Node *tempPtr = head;

	while(tempPtr != NULL)
	{
		if(tempPtr->data == x)
		{
			return true;
			break;
		}
		else
			tempPtr = tempPtr->next;
	}
	
	if(tempPtr == NULL)
		return false;

	delete tempPtr;
	*/
	return true;
}

void List::MakeEmpty()
{
/*
Pre: List is not empty
Post: List is now empty
*/
	/*
	Node *tempPtr = head;

	while(head != NULL)
	{
		head = head->next;
		delete tempPtr;
		length--;
	}
	*/
}

void List::Directions()
{
	cout << "DIRECTIONS:\n\n"
		 << "Type in the function you wish to perform in all\n"
		 << "capital letters then press ENTER. Place no spaces\n"
		 << "in words typed in. Enter EXIT when finished.\n\n"
		 << "*** For a list of usable functions type in FUNCTIONLIST ***\n\n";
}
void List::FunctionList()
{
	string functions[] = {"INSERT", "DELETE", "PRINT", "GETLENGTH", "ISTHERE"};

	for(int i = 0; i < 5; i++)
	{
		cout << functions[i] << endl;
	}
	cout << endl;
}
void List::Interface()
{
	string function;

	while(function != "EXIT")
	{
		cout << "=> ";
		cin  >> function;

		if(function == "INSERT")
			Insert();
		else if(function == "FUNCTIONLIST")
			FunctionList();
		else if(function == "GETLENGTH")
			GetLength();
		else if (function == "EXIT")
		{

		}		
		else
		{
			cout << "*** FUNCTION DOES NOT EXIST ***\n"
				 << "	   *** TRY AGAIN ***\n";
		}
	}
}
void List::Save(ofstream &outData)
{
	Node *newPtr = head;
	
	while(newPtr != NULL)
	{
		outData << newPtr->Brand << endl;
		outData << newPtr->Name << endl;
		outData << newPtr->Price << endl;
		outData << newPtr->DrawRating << endl;
		outData << newPtr->AromaRating << endl;
		outData << newPtr->TasteRating << endl;
		newPtr = newPtr->next;
	}

	outData.close();
}
void List::Upload(fstream &inData)
{
	//Uploads contents of file to linked list
	string brand, name;
	double price, taste, draw, aroma;

	while(inData)
	{
		inData >> brand;
		//cout << brand << endl;
		inData >> name;
		//cout << name << endl;
		inData >> price;
		//cout << price << endl;
		inData >> draw;
		//cout << draw << endl;
		inData >> aroma;
		//cout << aroma << endl;
		inData >> taste;
		//cout << taste << endl;
	}

	inData.close();
}




Is This A Good Question/Topic? 0
  • +

Replies To: File I/O Problem

#2 Pontus  Icon User is offline

  • Cattlebruiser

Reputation: 18
  • View blog
  • Posts: 612
  • Joined: 28-December 06

Re: File I/O Problem

Posted 21 August 2009 - 01:54 AM

Instead of
while(inData)
use
while(!inData.eof())

This post has been edited by Pontus: 21 August 2009 - 01:55 AM

Was This Post Helpful? 0
  • +
  • -

#3 UofMCreed  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: File I/O Problem

Posted 21 August 2009 - 02:04 AM

View PostPontus, on 21 Aug, 2009 - 12:54 AM, said:

Instead of
while(inData)
use
while(!inData.eof())


I tryed your change, same problem still exists. Thnx for the help though!
Was This Post Helpful? 0
  • +
  • -

#4 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 291
  • View blog
  • Posts: 1,900
  • Joined: 25-October 06

Re: File I/O Problem

Posted 21 August 2009 - 03:19 AM

View PostUofMCreed, on 21 Aug, 2009 - 08:04 AM, said:

View PostPontus, on 21 Aug, 2009 - 12:54 AM, said:

Instead of
while(inData)
use
while(!inData.eof())


I tryed your change, same problem still exists. Thnx for the help though!

you have opened the same file for input and output which could cause problems
open it for input read the data close it and then open it for output, e.g.
try
inData.open("Cigars.txt");//For retrieving information from file
list.Upload(inData);
inData.close();
outData.open("Cigars.txt");//For saving to the file
list.Directions();
list.Interface();
list.Save(outData);


also your UpLoad() is reading data into local variables - you need to add the data to your linked list
Was This Post Helpful? 1
  • +
  • -

#5 UofMCreed  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: File I/O Problem

Posted 21 August 2009 - 12:43 PM

View Posthorace, on 21 Aug, 2009 - 02:19 AM, said:

View PostUofMCreed, on 21 Aug, 2009 - 08:04 AM, said:

View PostPontus, on 21 Aug, 2009 - 12:54 AM, said:

Instead of
while(inData)
use
while(!inData.eof())


I tryed your change, same problem still exists. Thnx for the help though!

you have opened the same file for input and output which could cause problems
open it for input read the data close it and then open it for output, e.g.
try
inData.open("Cigars.txt");//For retrieving information from file
list.Upload(inData);
inData.close();
outData.open("Cigars.txt");//For saving to the file
list.Directions();
list.Interface();
list.Save(outData);


also your UpLoad() is reading data into local variables - you need to add the data to your linked list


Thanks again for the help, it put me one ste closer but there is still a bug in it. It only grabs the data in the fle if I just created it on the previous run. When it grabs the data, the data is outputted twice. And when I put the code in to insert into the linked list the program doesnt run at all.
Was This Post Helpful? 0
  • +
  • -

#6 UofMCreed  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: File I/O Problem

Posted 21 August 2009 - 12:49 PM

UPDATED UPLOAD FUNCTION
void List::Upload(ifstream &inData)
{
	//Uploads contents of file to linked list
	string brand, name;
	double price, taste, draw, aroma, overall;
	Node *newPtr = head;

	while(!inData.eof())
	{
		inData >> brand;
		//newPtr->Brand = brand;
		cout << brand << endl;

		inData >> name;
		//newPtr->Name = name;
		cout << name << endl;

		inData >> price;
		//newPtr->Price = price;
		cout << price << endl;

		inData >> draw;
		//newPtr->DrawRating = draw;
		cout << draw << endl;
		
		inData >> aroma;
		//newPtr->AromaRating = aroma;
		cout << aroma << endl;
		
		inData >> taste;
		//newPtr->TasteRating = taste;
		cout << taste << endl;

		inData >> overall;
		//newPtr->OverallRating = overall;
		cout << overall << endl;

		length++;
	}
	head = newPtr;
	delete newPtr;
}




AM I MISSING SOMETHING REALLY SIMPLE CAUSE IM NOT UNDERSTANDING THE PROBLEM I AM HAVING. HELP ME PLZ!

This post has been edited by UofMCreed: 21 August 2009 - 12:52 PM

Was This Post Helpful? 0
  • +
  • -

#7 UofMCreed  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: File I/O Problem

Posted 22 August 2009 - 12:12 AM

FOR SOME REASON IN MY Upload() FUNCTION, MY WHILE LOOP LOOPS AN EXTRA TIME WHEN IT GETS TO THE END OF THE FILE. CAN ANYONE HELP?
Was This Post Helpful? 0
  • +
  • -

#8 farhanhubble  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 15-April 09

Re: File I/O Problem

Posted 22 August 2009 - 01:15 AM

Although I use C i have this solution that I think will fix the one extra execution of the while loop.

The end of file is true only if the last read failed.

You should check for eof just after reading a line and before performing any actions on the the values, to see if eof becomes true. If it does you should immediately break out of the while loop.

If you perform the check after performing some actions e.g. printing the values just read before checking for an eof it will invariably cause an extra line to be printed.

I present both the correct and the incorrect versions below. Although they are in C I hope it will help you understand the logic.

Although EOF is read in both the cases the first code checks for valid data before printing it while the second while loop performs this checks only after printing the data.


FILE *fp;

fp = fopen("filename","mode"); // open stream for reading


/***********correct***************/

while(1)
{
		  fscanf("%d %d %d",&vara,&varb,&varc); //try reading a line
		  
		   if(eof(fp))		   //if the line just read was end of file
		   {
				break;		   //break out of the while loop
			}
		/****print only after the check has been performed**/
		
		   printf("%d %d %d",vara,varb,varc);


}


/***************incorrect************/

while( !eof(fp))
{
		   fscanf("%d %d %d",&vara,&varb,&varc);
			printf("%d %d %d",vara,varb,varc);
}





The last version is buggy. Because when the last [b] valid[\b] line is read eof(fp) is false because the end of file hasn't been reached. So the while loop executes once more reading EOF and storing unwanted data into the variables etc. It is only now that eof(fp) becomes true and the while loop ends.

I hope this helps
Was This Post Helpful? 0
  • +
  • -

#9 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6110
  • View blog
  • Posts: 23,667
  • Joined: 23-August 08

Re: File I/O Problem

Posted 22 August 2009 - 07:20 AM

UofMCreed ... read.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1