GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 06-May-2008, 07:45
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

outputting a class from a linked list


i am writing a program to perform various functions on some inputted shapes (for a course im taking) and have hit a bit of a brick wall...
was wondering if anyone here could help.

my problem is this; i have a list of rectangles stored in a linked list and need to output the details of said rectangles using a display list function. within the the display list function i would like to access either the "id" of the shape (that being an arbitart counter used to identify the shape) or print out all the details of the shape using a showinfo() function.
just when i thought i was making progress i got a random break/error when i came to displaying the list. the debugger just said "unspecified error".

CPP / C++ / C Code:
#include <iostream>
#include "LinkedList.h"
#include "rect.h"
#include "cube.h"
#include "shape.h"
using namespace std;


void createrect(LinkedList<rect*> &ListOfrects);


void main(void){

	LinkedList<rect*> ListOfrects;



	char menu;//PRIMARY MENU, CHOOSE YOUR SHAPE
	cout << "\n\tWelcome to Sams Super Shape Manipulator & Calculator!!\n\n";
	cout << "what kind of shape would you like to do?" <<endl;	
	cout << "\nC. Create new Shape\n" ;
	cout << "E. Edit saved Shapes\n"; 
	cout << "Q. To Quit Program\n";
	cin >> menu;

	while(menu != 'q' && menu != 'Q'){        
		switch(menu){
		case 'C':
		case 'c':
			char menuC;              
			cout << "\nPlease chose one of the following\n" ;
			cout << "A. Create new Rectangle\n" ;
			cout << "Q. To Exit to Main Menu\n";
			cin >> menuC;


			while(menuC != 'q' && menuC != 'Q'){
				switch(menuC){
		case 'A':
		case 'a':
			createrect(ListOfrects);
			
			//insert other shapes here
		case 'Q':
		case 'q': 
			break;
				}
				
				//end create shapes
			cout << "\nPlease chose one of the following\n" ;
			cout << "A. Create new Rectangle\n" ;
			cout << "Q. To Exit to Main Menu\n";
			cin >> menuC;

		case 'Q':
		case 'q': 
			break;
			}//end create menu
		
			cout << "\n\tWelcome to Sams Super Shape Manipulator & Calculator!!\n\n";
	cout << "what kind of shape would you like to do?" <<endl;	
	cout << "\nC. Create new Shape\n" ;
	cout << "E. Edit saved Shapes\n"; 

	cout << "Q. To Quit Program\n";
	cin >> menu;

		case 'E':
		case 'e':
			char menuE;
			cout << "\nPlease chose the type of shape you would like to Edit\n";
			cout << "A. Regtangle \n";
			cout << "Q. To Exit to Main Menu\n";
			cin >> menuE;
			while(menuE != 'q' && menuE != 'Q'){  
				switch(menuE){


		case 'a':
		case 'A':
			double optrec;
			cout << "\n";
			ListOfrects.displayList();//// PROGRAM CRASHES HERE DUE TO DISPLAYLIST
			cout << "\n";
			cout << "Please enter the ID of the Regtangle you wish to Edit\n";
			cin >> optrec;
			rect *temp;
			rect temp2 (optrec, 0,0);
			temp = &temp2;
			ListOfrects.findNode(temp);
			char optEd2;
			cout << "\nPlease chose which from the following\n";
			cout << "\nA. To Edit ID";
			cout << "\nB. To Create a 3D Prism";
			cout << "\nQ. To go back.";
			cin >> optEd2;
			while(optEd2 != 'q' && optEd2 != 'Q'){
				switch(optEd2){
		case'A':
		case'a':
			double setS;
			cout << "\nPlease enter new value\n" ;
			cin >> setS;       
			rect *temp;
			rect temp2 (optrec, 0,0);
			temp = &temp2;
			ListOfrects.findNode(temp);
//			setID(setS);
			break;
			/*case'B':
			case'b':
			createCube(ListOfCubes);
			cout << "\nPrism created\n";
			break;                       */                           
//		default:
			break; 
				}
				cout << "\nPlease chose which from the following\n";
				///cout << "\nA. To Edit ID";
				cout << "\nB. To convert to 3D Prism";
				cout << "\nQ. To go back\n";
				cin >> optEd2;  
			}

			break;
				}
			}
		}//menu1 choices
	}//end menu1
}//end of main

void createrect(LinkedList<rect*> &ListOfrects){
	rect *temp;
	double val;
	double w(0), l(0);    
	// ask the user to produce some values
	// put them in the list
	for (;;) {
		cout << "\nRectangle ID (0 to stop): ";
		cin >> val; 
		if (val == 0){break;} 
		rect temp2 (val, 0,0);
		temp = &temp2;
		ListOfrects.appendNode(temp);
		cout << "rect Width: " ;
		cin >> w;
		temp->setWidth(w);
		cout << "rect Length: ";
		cin >> l;
		temp->setLength(l);
		temp->setarea(); 
	}}


CPP / C++ / C Code:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template <class T>
class LinkedList
{
private:
	// Declare a structure for the list
	struct ListNode
	{
		T value;
		struct ListNode *next;
	};
	ListNode *head; // List head pointer

public:
	LinkedList(void) // Constructor
	{ head = NULL; }
	~LinkedList(void); // Destructor
	void appendNode(T);
	void insertNode(T);
	void deleteNode(T);
	void displayList(void);
	void findNode(T);
};

	// appendNode appends a node containing the
	// value pased into num, to the end of the list.
	template <class T>
		void LinkedList<T>::appendNode(T num)
	{
		ListNode *newNode, *nodePtr;
		// Allocate a new node & store num
		newNode = new ListNode;
		newNode->value = num;
		newNode->next = NULL;

		// If there are no nodes in the list
		// make newNode the first node
		if (!head)
			head = newNode;
		else // Otherwise, insert newNode at end
		{ // Initialize nodePtr to head of list
			nodePtr = head;
			// Find the last node in the list
			while (nodePtr->next)
				nodePtr = nodePtr->next;
			// Insert newNode as the last node
			nodePtr->next = newNode;
		}
	}

template <class T>
void LinkedList<T>::displayList()
{
	ListNode *nodePtr;
	nodePtr = head;
	while (nodePtr)
	{
	nodePtr->value->ShowInfo();    ////WHERE I PUT MY SHOWINFO FUNCTION IN
	nodePtr = nodePtr->next;
	}
}

	// The insertNode function inserts a node with
	// num copied to its value member.
	template <class T>
		void LinkedList<T>::insertNode(T num)
	{
		ListNode *newNode, *nodePtr, *previousNode;
		// Allocate a new node & store Num
		newNode = new ListNode;
		newNode->value = num;
		// If there are no nodes in the list
		// make newNode the first node
		if (!head)
		{
			head = newNode;
			newNode->next = NULL;
		}
		else // Otherwise, insert newNode at end
		{
			// Initialize nodePtr to head of list
			nodePtr = head;
			// Skip all nodes whose value member is less
			// than num.
			while (nodePtr != NULL && nodePtr->value < num)
			{
				previousNode = nodePtr;
				nodePtr = nodePtr->next;
			}
			// Insert the node after the one pointed to
			// by previousNode and before the one pointed to
			// by nodePtr.
			previousNode->next = newNode;
			newNode->next = nodePtr;
		}
	}

	//The deleteNode function searches for a node
	// with Num as its value. The node, if found, is
	// deleted from the list and from memory.
	template <class T>
		void LinkedList<T>::deleteNode(T num)
	{
		ListNode *nodePtr, *previousNode;
		// If the list is empty, do nothing.
		if (!head)
			return;
		// Determine if the first node is the one.
		if (head->value == num)
		{
			nodePtr = head->next;
			delete head;
			head = nodePtr;
		}
		else
		{
			// Initialize nodePtr to head of list
			nodePtr = head;
			// Skip all nodes whose value member is
			// not equal to num.
			while (nodePtr != NULL && nodePtr->value != num)
			{
				previousNode = nodePtr;
				nodePtr = nodePtr->next;
			}
			// Link the previous node to the node after
			// nodePtr, then delete nodePtr.
			previousNode->next = nodePtr->next;
			delete nodePtr;
		}
	}

template <class T>
void LinkedList<T>::findNode(T num)
{
	int count = 0;
	ListNode *nodePtr, *previousNode;
 
	// If the list is empty, do nothing.
	if ( !head )
		return;

	// Initialize nodePtr to head of list
	nodePtr = head;

	// Skip all nodes whose value member is 
	// not equal to searchValue.
	while (nodePtr != NULL && nodePtr->value != num)
	{  
		nodePtr = nodePtr->next;
		count++;
	}

	if ( ! nodePtr ) //didn't find the value and arrived at the end
	{
		cout << "your number was not found" << endl;
	}
	else
	{
		cout << "your number is in index:" << count + 1 << endl;
		cout << "Value: " << nodePtr->value << endl;
		cout << nodePtr->value << endl;
	}
}

	// Destructor
	// This function deletes every node in the list.
	template <class T>
		LinkedList<T>::~LinkedList(void)
	{
		ListNode *nodePtr, *nextNode;
		nodePtr = head;
		while (nodePtr != NULL)
		{
			nextNode = nodePtr->next;
			delete nodePtr;
			nodePtr = nextNode;
		}
	};
#endif

as far as im aware this is the only problem currently, though im far from finished. if you need copies of anything else please let me know.

oh, my showinfo looks like:

CPP / C++ / C Code:
void rect::ShowInfo(){
     cout << " rectangle ID is  " << ID << "\n";
      cout << "This rectangles Width is " << width << "\n";
     cout << "This rectangles Length is " << length << "\n";
      cout << "This rectangles Area is " << area << "\n";
}

any help appreciated

thanks

Sam

edit: highlighted where my problems are, as i put quite a lot of code up there
  #2  
Old 06-May-2008, 09:15
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: outputting a class from a linked list


Quote:
Originally Posted by molemanuk
i am writing a program... i have a list of rectangles stored in a linked list...
Maybe I'm missing something, but I see a linked list of pointers to rectangles.

When you add a rectangle to the list, here is what I see:

1. In createrect, you create a rect object named temp2, The object's scope is local to that function.

2. You send the address of this object to appendNode

3. In appendNode you create a ListNode struct and set its value member equal to the address of the temporary object whose address the appendNode function received.

4. The new node is appended to the list.

5. After appendNode returns, you get user information for width and height and store them in the temporary struct that is pointed to by the last element of the list.

6. When the function createrect returns, the temporary struct goes out of scope, so the pointer to it no longer points to valid memory.

7. After leaving createrect you try to print out values of some things that are not in valid memory. The result is undefined behavior, and that means that just about anything could happen. Successive program runs could give different results, depending on what else is happening in your system.

In other words:

Why the heck did you make a linked list of [i]pointers[/I to rects? Why not just make a linked list of rects? You could have the head pointing to a rect object (Instead of having it point to a pointer to a rect). Each rect object would have a pointer member that points to the next rect in the list.

Now, I could be missing something (but I have already said that). However, if, for some reason, you absolutely have to have a list of pointers, then you had better make damn sure that each pointer actually points to something in valid memory.

Regards,

Dave
  #3  
Old 06-May-2008, 09:42
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

Re: outputting a class from a linked list


hmm, i was wondering why i get nothing when i try to output it... im not very good with pointers, i find them to be, shall we say, one of the more challenging aspects of programming.

ill have a jiggle around with them see if it helps. will be tomorrow now though as i dont have access to much in the way of a compiler at home.
thanks for your help ill post again tomorrow and let you know how i get on.

Sam
  #4  
Old 07-May-2008, 05:15
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

Re: outputting a class from a linked list


ok iv had a quick jiggle about with the createrect function and think iv kinda got that sorted, i just dont quite know how to change my appendnode function now to let it take actual objects... i copied most of linkedlist.h from a txt book and the explanation wasnt particulary good. i now get


error C2664: 'LinkedList<T>::appendNode' : cannot convert parameter 1 from 'rect *' to 'rect' with [ T=rect ]
and
error C2664: 'LinkedList<T>::findNode' : cannot convert parameter 1 from 'rect *' to 'rect' with [ T=rect ]

error messages. here's what the relevant code looks like now

CPP / C++ / C Code:
case 'a':
		case 'A':
			double optrec;
			cout << "\n";
			ListOfrects.displayList();
			cout << "\nPlease enter the ID of the Regtangle you wish to Edit\n";
			cin >> optrec;
			rect *temp;
			temp = new rect(optrec,0,0);
			ListOfrects.findNode(temp);	
			char optEd2;
			cout << "\nPlease chose which from the following\n";
			cout << "\nA. To Edit ID";
			cout << "\nB. To Create a 3D Prism";
			cout << "\nQ. To go back.";
			cin >> optEd2;

			while(optEd2 != 'q' && optEd2 != 'Q'){
				switch(optEd2){
		case'A':
		case'a':
			double setS;
			cout << "\nPlease enter new value\n" ;
			cin >> setS;       
			rect *temp;
			temp = new rect(optrec,0,0);
			ListOfrects.findNode(temp);	
			temp->setID(setS);
			break;


	/*	case'Q':
		case'q':	
			break; */
				}
				cout << "\nPlease chose which from the following\n";
				cout << "\nA. To Edit ID";
				//cout << "\nB. To convert to 3D Prism";
				cout << "\nQ. To go back\n";
				cin >> optEd2;  
			}

			break;
				}
			}
		}//menu1 choices
	}//end menu1
}//end of main

void createrect(LinkedList<rect>& ListOfrects)
{
	rect * temp;
	double val;
	double w, l;

	// ask the user to produce some values
	// put them in the list
	for (;;)
	{
		cout << "\nRect ID (0 to stop): ";
		cin >> val;
		if (val==0){break;}
		temp = new rect(val,0,0);
		ListOfrects.appendNode(*temp);
		cout << "rect Width: " ;
		cin >> w;
		temp->setWidth(w);
		cout << "rect Length: ";
		cin >> l;
		temp->setLength(l);
		temp->setarea();

	}

}

with linkedlist.h and the rest of my main the same as before. any help is appreciated.

thanks again

Sam

edit, added some more of my code in, specifically the bits that display and findlist
  #5  
Old 07-May-2008, 05:33
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

Re: outputting a class from a linked list


im also having trouble with the output still. something is wrong with my displaylist function

CPP / C++ / C Code:
template <class T>
void LinkedList<T>::displayList()
{
	ListNode *nodePtr;
	nodePtr = head;
	while (nodePtr)
	{
	cout << nodePtr->value->ShowInfo() << endl;
        nodePtr = nodePtr->next;
	}
}

i only get these error messages if i comment out the findNode bits in my main which are still throwing up cannot convert from object to pointer errors.

error C2819: type 'rect' does not have an overloaded member 'operator ->'
error C2227: left of '->ShowInfo' must point to class/struct/union

as far as i can see (unless im missing something) rect has a member function of showinfo and i dont think iv ever overloaded a pointer opperator... so i dont quite know how to go about doing that.
  #6  
Old 07-May-2008, 07:48
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

Re: outputting a class from a linked list


i understand that im trying to output a rect class using this but i thought that the fact it was a template would solve the problem... cant seem to fix it. iv tried all my usual tricks with no luck...
  #7  
Old 07-May-2008, 12:12
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: outputting a class from a linked list


Quote:
Originally Posted by molemanuk
im also having trouble

error C2819: type 'rect' does not have an overloaded member 'operator ->'
error C2227: left of '->ShowInfo' must point to class/struct/union

as far as i can see (unless im missing something) rect has a member function of showinfo and i dont think iv ever overloaded a pointer opperator... so i dont quite know how to go about doing that.

If you have a pointer to an object, you access its members with ->

If you have an object, you acces its members with. (a dot)

Regards,

Dave
  #8  
Old 08-May-2008, 07:47
molemanuk molemanuk is offline
New Member
 
Join Date: May 2008
Posts: 6
molemanuk is on a distinguished road

Re: outputting a class from a linked list


ok, i kinda started this again and came at it from a differant angle, solving my problems for the most part.
BUT

im now having trouble getting the program to store my date.
once its entered it is appended to the list and that works fine, but im trying to come up with a semi-decent menu system that allows me to delete shapes, edit shapes etc
when i break out of the loop that allows me to input the shapes, the data is lost (goes out of scope??)

here's my main file (which as far as i can see is where the problem lies)

thanks for the previous posts btw, they did help for a time.

CPP / C++ / C Code:
#include <iostream>
#include "rect.h" // includes all the header files
#include "Circle.h"
#include "Cube.h"
#include "Sphere.h"
#include "Triangle.h"
#include "LinkedList.h"
#include "Prism.h"
using namespace std;

double temporaynumber;
Rect Recc[20];Circle Circ[20];Cube Cubo[20];Sphere Spher[20];Triangle Tri[20];Prism prism[20]; // creates arrays of shapes 20, was chosen as an abitary number
int RecCount=0,CircCount=0,CubeCount=0,SpheCount=0,TriCount=0,Input,Input2; // creates counters and inputs
int tempcount[20],inputnumber,inputnumber2;
bool condition=false,condition2=true,condition3=false,condition4=true; // these are used in the while loops
char str[20];
LinkedList<Shape*> list; // creates the linked list
Shape* shapepointer; // this pointer will be used to add shapes to the linked list


void main_menu();
void create_menu();
void delete_menu();

void main(void){
	string error1= "\nYou have entered an inccorect input please enter a valid number" ; // standard error conditong

main_menu:
	int main_menu_choice;
	main_menu();
	cin >> main_menu_choice;

	if(main_menu_choice == 1){
create_menu:
condition=false,condition2=true;
		create_menu();
		int create_menu_choice;
		cin >> create_menu_choice;

		while ( condition == false){
			condition2 = true;

			if (create_menu_choice == 1){
				++RecCount;
				cout << " \n1. Rect" << endl;
				cout << "\nWidth: "; cin >> temporaynumber;	Recc[RecCount].setWidth(temporaynumber);
				cout << "Length: "; cin >> temporaynumber; Recc[RecCount].setLength(temporaynumber);
				Recc[RecCount].setnumber(RecCount);
				Recc[RecCount].setname("Rect");
			}

			else if (create_menu_choice == 3){
				++CircCount;
				cout << " \n3. Circle;" << endl;
				cout << "\nRadius: "; cin >> temporaynumber; Circ[CircCount].setRadius(temporaynumber);
				Circ[CircCount].setnumber(CircCount);
				Circ[CircCount].setname("Circle");
			}
			else if (create_menu_choice == 2){
				++CubeCount;
				cout << " \n2. Cuboid;" << endl;
				cout << "\nWidth: "; cin >> temporaynumber;	Cubo[CubeCount].setWidth(temporaynumber);
				cout << "Length: "; cin >> temporaynumber; Cubo[CubeCount].setLength(temporaynumber);
				cout << "height: "; cin >> temporaynumber; Cubo[CubeCount].setHeight(temporaynumber);
				Cubo[CubeCount].setnumber(CubeCount);
				Cubo[CubeCount].setname("Cuboid");
			}
			else if (create_menu_choice == 4){
				++SpheCount;
				cout << " \n4. Sphere;" << endl;
				cout << "\nRadius: "; cin >> temporaynumber;Spher[SpheCount].setRadius(temporaynumber);
				Spher[SpheCount].setnumber(SpheCount);
				Spher[SpheCount].setname("Sphere");
			}
			else if (create_menu_choice == 5){
				++TriCount;
				cout << " \n5. Triangle;" << endl;
				cout << "\nBase: "; cin >> temporaynumber;	Tri[TriCount].setBase(temporaynumber);
				cout << "Length: "; cin >> temporaynumber; Tri[TriCount].setLength(temporaynumber);
				Tri[TriCount].setnumber(TriCount);
				Tri[TriCount].setname("Triangle");
			}
			else if (create_menu_choice == 0){ goto main_menu;}

			else{cout << error1 << endl;}

			while( condition2 == true){
				cout << "\nWould you like to input more shapes? Yes(1),No(2):" << endl;
				cin >> str;
				if (isdigit(str[0]) > 0){Input2 = atoi(str);} else Input2 = 0;// Prevents chracter input
				if (Input2 == 1){condition = false;condition2 = false;} // Continues looping
				else if (Input2 == 2){condition = true;condition2 = false;
				goto create_menu;} // Stops the looping and goes to the main menu
				else{cout <<  error1 << endl;}} // error conditon

		}//end while - the one that lets you enter more shapes

		for (int i=1; i < RecCount+1; ++i){ 
			shapepointer = &Recc[i];
			list.AppendNode(shapepointer);}

		for (int i=1; i < CircCount+1; ++i){ 
			shapepointer = &Circ[i];
			list.AppendNode(shapepointer);}

		for (int i=1; i < CubeCount+1; ++i){ 
			shapepointer = &Cubo[i];
			list.AppendNode(shapepointer);}

		for (int i=1; i < TriCount+1; ++i){ 
			shapepointer = &Tri[i];
			list.AppendNode(shapepointer);}

		for (int i=1; i < SpheCount+1; ++i){ 
			shapepointer = &Spher[i];
			list.AppendNode(shapepointer);}
	}//end create menu
	else if(main_menu_choice == 2){
delete_menu:
		//condition3=false,condition4=true;
		cout << "the shapes so far are:"<<endl;
list.DisplayList(); ////HERE IS WHERE ITS SUPPOSED TO DISPLAY MY SHAPES, BUT IT DOESNT...
	delete_menu();
	int delete_menu_choice;
	cin >> delete_menu_choice;
}//end delete menu if loop.
}//end main

any advice would be welcommed. im wondering if it's because iv used the goto function, as it goes back to the start of the program... if it is, any suggestions as to how else to do it would be good as iv tried using break and it just seems to end my program. i have also tried using a switch system but i just cant seem to get it to work as once again when i break out of the loop it loses all the data.

thanks again.

Sam

p.s. i should point out that the rest of my code DOES work, and if i put my displaylist inside the create part of the program it works.
 
 

Recent GIDBlogInstall Adobe Flash - Without Administrator Rights by LocalTech

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Str_Misaligned in Double Link List Peter_APIIT C Programming Language 1 29-Feb-2008 20:50
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 07:44
Hard drive/CPU Diagnoses Issues binarybug Computer Hardware Forum 1 22-Jan-2007 19:23
C++ class -- Please help vnca_1 C++ Forum 3 14-Jun-2006 12:31

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 06:27.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.