1,105,271 Community Members

trying to insert a new node into a linkedlist

Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok, so I am befuddled. Each individual file compile fine, no errors. When I compile all together and create an executable, no errors. But, when I run the program, I am getting an error. I have it narrowed down to a problem with my void LinkedList::insert(const ElementType &dataValue) but I have looked at it too many time to figure out what's wrong. The main concept is that a new node will be inserted in a sorted order based on the key of a struct. The linked list is sorted alphabetically. Also attached is a sample of the data being read in.

/*~~~linkedlist.h~~~~*/
#include <iostream>
#include <string>
using namespace std;

typedef struct Articles ElementType;
typedef std::string KeyType;

struct Articles
{
	string key;
	string name;
	string title;
};

class LinkedList
{
	private:
		class Node
		{
		public:
			ElementType data;
			Node * next;
			Node(ElementType dataValue){		
				data = dataValue;
				next = NULL;
			}
		};
		typedef Node * NodePointer;
		Node *find (const KeyType &key);
		NodePointer first;
		int mySize;
		int index;
	public:
		LinkedList();
		void insert (const ElementType &item);
		bool find (const KeyType &key, ElementType &item);
		bool erase (const KeyType &key);
};
		bool operator==(const ElementType &e1, const KeyType &key);
		bool operator>=(const ElementType &e1, const KeyType &key);
/*~~~linkedlist.cpp~~~~*/
#include <iostream>
using namespace std;
#include "linkedlist.h"

LinkedList::LinkedList()
{
	first = NULL;
	mySize = 0;
}

void LinkedList::insert(const ElementType &dataValue)
{
	NodePointer nPtr = new Node(dataValue);
	NodePointer predPtr = first;
	if (first->next == NULL)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else
	{
		while ((dataValue.key) >= predPtr->data.key)
		{
			predPtr=predPtr->next;
		}
		if ((dataValue.key) == predPtr->next->data.key)
		{
			nPtr->next = predPtr->next;
			predPtr->next = nPtr;
		}
	}
}

bool LinkedList::find(const KeyType &key, ElementType &item)
{
}

bool LinkedList::erase(const KeyType &key)
{
}

bool operator==(const ElementType &e1, const KeyType &key)
{
	if (e1.key == key)
		return true;
	else
		return false;
}

bool operator>=(const ElementType &e1, const KeyType &key)
{
	if (e1.key >= key)
		return true;
	else
		return false;
}
/*~~~program2.cpp~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 |     A driver file which plays a game of Tic Tac Toe with two        |
 |  players. The program incorporates 2 classes (and header            |
 |  files for each): Tictactoe and Player. Tictactoe handles           |
 |  the displayBoard(), setValue(), and getStatus() functions.         |
 |  The Player class handles getName(), getIndex(), and                |
 |  getMove() functions. Definition of the functions are in            |
 |  their corresponding .cpp/.h files.                                 |
 |     Game play consists of receiving a player's name then            |
 |  determining which player goes first. The players, starting         |
 |  with the first player, will be prompted to enter a position        |
 |  which will be checked for whether: the space is out of the         |
 |  scope and whether the space is already occupied, and if            |
 |  neither is the case, the spot will be marked with the player's     |
 |  mark (X or O). Then the program will check if there is a win,      |
 |  a tie, or other(results in continuing game play). A win can        |
 |  be from either player and is checked after each player's "turn."   |
 |  The game board is displayed at the beginning (with no X's or O's)  |
 |  and after each player's turn.                                      |
 |                                                                     |
 |  Author: Megan MacDonald                                            |
 |  Date Completed: ---, 2009                                      |
 |  Class: CSC 2110, section 002                                       |
 |  Tennessee Technological University                                 |
 |                                                                     |
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "linkedlist.h"

int main()
{
	LinkedList l;
	ifstream inFile("cacmpubshort.txt");
	Articles s;
	if (inFile.is_open())
	{
		while (!inFile.eof())
		{
			getline (inFile,s.key);
			getline (inFile,s.name);
			getline (inFile,s.title);
			cout << s.key << "    " << s.name << "    " << s.title << endl;
			l.insert(s);
		}
		inFile.close();
	}
	else cout << "Unable to open file";
	return 0;
}

~~~~cacmpubshort.txt~~~~~

Crawford:2000:EPa
Diane Crawford
Editorial pointers
Fox:2000:NTCa
Robert Fox
News Track: Celestial backbone; Foreign hands off China's net; Women and the web; DOE says no nuke access; Worst net nightmare; Sidebar: Ethics quiz
Crawford:2000:FTO
Diane Crawford and Brian K. E. Balke and Steve Wilstrom and Jef Raskin and Pat McGee
Forum: Tackling OO Design Principles; Educational Concerns; Building LEGO Robots
Meeks:2000:EFBa
Brock N. Meeks
Electronic frontier: bugging out: Y2K fallout or business as usual?
Soloway:2000:LEK
Elliot Soloway and Cathleen Norris and Phyllis Blumenfeld and Barry Fishman and Joseph Krajcik and Ronald Marx
Log on Education: K--12 and the Internet
Porter:2000:SCL
Tom Porter and Galyn Susman
On site: creating lifelike characters in Pixar movies
Simons:2000:PBB
Barbara Simons
From the President: building Big Brother
Konana:2000:IOI
Prabhudev Konana and Nirup M. Menon and Sridhar Balasubramanian
The implications of online investing
Gorriz:2000:EGC
Cecilia M. Gorriz and Claudia Medina
Engaging girls with computers through software games
Hargittai:2000:RLI
Eszter Hargittai
Radio's lessons for the Internet
Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

another thing to add - when i run the program, this is the error

Crawford:2000:EPa Diane Crawford Editorial pointers
3 [main] program2 3416 _cygtls::handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
619 [main] program2 3461 open_stackdumpfile: Dumping stack trace to program2.exe.stackdump
21228 [main] program2 3461 _cygtls::handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
22159 [main] program2 3461 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack)

Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

ok so i fiddle with it some more, managed to get the first node into the list ...here's the insert function (i didn't change any other parts of the program)

void LinkedList::insert(const ElementType &dataValue)
{
	NodePointer nPtr = new Node(dataValue);
	NodePointer predPtr = first;
	if (first == NULL)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else
	{
		while ((dataValue.key) >= predPtr->data.key)
		{
			predPtr=predPtr->next;
		}
		if ((dataValue.key) == predPtr->next->data.key)
		{
			nPtr->next = predPtr->next;
			predPtr->next = nPtr;
		}
	}
	cout << dataValue.key << " " << dataValue.name << " " << dataValue.title << endl;
}

*note:error is the same as before**, but i know that the problem lies with in the while ((dataValue.key) >= predPtr->data.key) and if ((dataValue.key) == predPtr->next->data.key) lines...

**same wording different numbers
3 [main] program2 944 _cygtls::handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
679 [main] program2 944 open_stackdumpfile: Dumping stack trace to program2.exe.stackdump
37260 [main] program2 944 _cygtls::handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
38779 [main] program2 944 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack)

Member Avatar
siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,429 [?]
Q&As Helped to Solve: 142 [?]
Skill Endorsements: 11 [?]
 
0
 

What is this >>> NodePointer nPtr = new Node(dataValue);
what is NodePointer? I didn't see it declared in any of your code!

Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

typedef Node * NodePointer; NodePointer is a pointer to a type of class Node. Thus, NodePointer nPtr = new Node(dataValue); is declaring nPtr as type NodePointer, and it is being set to a new object of class Node, which is receiving the dataValue.

Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok...the insert function problem has been solved...

/*~~~linkedlist.h~~~*/
#include <iostream>
#include <string>
using namespace std;

typedef struct Articles ElementType;
typedef std::string KeyType;

struct Articles
{
	string key;
	string name;
	string title;
};

class LinkedList
{
	private:
		class Node
		{
		public:
			ElementType data;
			Node * next;
			Node(ElementType dataValue){		
				data = dataValue;
				next = NULL;
			}
		};
		typedef Node * NodePointer;
		Node *LinkedList::find(const KeyType key)
		{
			NodePointer ptr;
			ptr = first;
			while (ptr != NULL)
			{
				if (ptr->data.key == key)
					return ptr;
				else
					ptr = ptr->next;
			}
			if (ptr == NULL)
				return NULL;
		}
		NodePointer first;
		NodePointer predPtr;
		int mySize;
		int index;
	public:
		LinkedList();
		void insert (const ElementType &item);
		bool find (const KeyType key, ElementType &item);
		bool erase (const KeyType key);
		void display();
};
		bool operator<(const ElementType &e1, const KeyType &key);
		bool operator>=(const ElementType &e1, const KeyType &key);
/*~~~linkedlist.cpp~~~~~*/
#include <iostream>
#include <iomanip>
using namespace std;
#include "linkedlist.h"

LinkedList::LinkedList()
{
	first = NULL;
	mySize = 0;
}

void LinkedList::insert(const ElementType &dataValue)
{
	NodePointer nPtr = new Node(dataValue);
	predPtr = first;
	NodePointer afterPtr;
	if (first == NULL)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else if (predPtr->data >= nPtr->data.key)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else
	{
		while (!((predPtr->next == NULL) || (predPtr->next->data >= nPtr->data.key)))
		{
			predPtr=predPtr->next;
		}
		nPtr->next = predPtr->next;
		predPtr->next = nPtr;
	}
}

bool LinkedList::find(const KeyType key, ElementType &item)
{
	LinkedList::NodePointer ptr;
	ptr = first;
	while (ptr != NULL)
	{
		if (ptr->data.key == key)
			return true;
		else
			ptr = ptr->next;
	}
	if (ptr == NULL)
		return false;
}

bool LinkedList::erase(const KeyType key)
{
	
}

void LinkedList::display()
{
	LinkedList::NodePointer ptr;
	ptr = first;
	cout << "--------------------------------------------------------------------------------" << endl;
	cout << " Key                 Author                      Title                          " << endl;
	cout << "--------------------------------------------------------------------------------" << endl;
	while (ptr != NULL)
	{
		cout << left << setw(20) << ptr->data.key << " " << ptr->data.name << "    '" << ptr->data.title << "'" << endl;
		ptr = ptr->next;
	}
}

bool operator==(const ElementType &e1, const KeyType &key)
{
	if (e1.key == key)
		return true;
	else
		return false;
}

bool operator>=(const ElementType &e1, const KeyType &key)
{
	if (e1.key >= key)
		return true;
	else
		return false;
}
/*~~~program2.cpp~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 |                                                                     |
 |  Author: Megan MacDonald                                            |
 |  Date Completed: ---, 2009                                      |
 |  Class: CSC 2110, section 002                                       |
 |  Tennessee Technological University                                 |
 |                                                                     |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "linkedlist.h"

void menuDisplay();

int main()
{
	char ch;
	KeyType findKey;
	KeyType srchKey;
	KeyType addKey;
	bool menuActive;
	
	LinkedList l;
	cout << "$ cacmLibrary cacmpub.txt" << endl
	<< "Loading library please wait..." << endl;
	ifstream inFile("cacmpubshort.txt");
	Articles s;
	if (inFile.is_open())
	{
		while (!inFile.eof())
		{
			getline (inFile,s.key);
			getline (inFile,s.name);
			getline (inFile,s.title);
			l.insert(s);
		}
		inFile.close();
	}
	else
	{
		cout << "Unable to open file";
	}
	
	cout << "Hello! Welcome to the CACM Library." << endl << endl;
	menuDisplay();
	
	menuActive = true;
	while (menuActive)
	{
		cout << "Your Choice:";
		cin.get(ch);
		cin.ignore(10,'\n');
		
		if (ch == 'f' || ch == 'F')
			{
				cout << "Find function selected." << endl;
				cout << "Please enter a search key:";
				cin >> srchKey;
				if (l.find(srchKey,s))
				{
					cout << "There is a record with that key." << endl;
				}
				else if (!l.find(srchKey,s))
				{
					cout << "*-------------------------------------------------------*" << endl;
					cout << "|  Sorry, but there are no records matching your query. |" << endl;
					cout << "*-------------------------------------------------------*" << endl;
				}
			}
		else if (ch == 'l' || ch == 'L')
			{
				cout << "List function selected." << endl;
				l.display();
			}
		else if (ch == 'a' || ch == 'A')
			{
				cout << "Add function selected." << endl;
				cout << "Enter the key for your new article:";
				cin >> addKey;
				if (l.find(addKey,s))
				{
					cout << "This key already exists!" << endl;
				}
				else if (!l.find(addKey,s))
				{
					s.key = addKey;
					cout << endl << "Enter the author's name:";
					cin >> s.name;
					cout << endl << "Enter the title of the article:";
					cin >> s.title;
					l.insert(s);
						cout << endl;
						cout << "*----------------------------------------*" << endl;
						cout << "| The following record has been ADDED    " << endl;
						cout << "|                                        " << endl;
						cout << "|    Key: " << s.key << endl;
						cout << "|  Title: " << s.title << endl;
						cout << "| Author: " << s.name << endl;
						cout << "*----------------------------------------*" << endl;
				}
			}
		else if (ch == 'r' || ch == 'R')
			cout << "Remove function selected." << endl;
		else if (ch == 'e' || ch == 'E')
		{
			cout << "Thank you for using the CACM Library!" << endl << "$" << endl;
			menuActive=false;
		}
		else if (ch != 'f' && ch != 'F' && ch != 'a' && ch != 'A' && ch != 'l' &&
		         ch != 'L' && ch != 'r' && ch != 'R' &&  ch != 'e' && ch != 'E')
			cout << "Invalid Choice." << endl;
	}
	return 0;
}

void menuDisplay()
{
	cout << "What would you like to do?" << endl << endl;
	
	cout << "*------------------------------*" << endl;
	cout << "| (F)ind an article            |" << endl
		 << "| (L)ist all articles          |" << endl
		 << "| (A)dd a new article          |" << endl
		 << "| (R)emove an existing article |" << endl
		 << "| (E)xit                       |" << endl;
	cout << "*------------------------------*" << endl << endl;
}
Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

****Note:

Program is not complete: I'm still working on bool erase (const KeyType key); AND I'm still trying to figure out how to incorporate my Node *LinkedList::find(const KeyType key) .... it's a private method that returns a Node that contains the article with the given key or NULL if the key is not found...
Any helpful suggestions would be greatly appreciated :)

Member Avatar
redhotspike
Newbie Poster
21 posts since Feb 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Alrighty: here's the completed program -- one issue left is that if there are 2 entries with the same key, the program won't find it. Also, after the third choice, user must enter their choice a second time. But these problems do not otherwise affect the program.

/*~~~linkedlist.h~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 |     A header file for data of type LinkedList. Private         |
 |  members include: Node *found(), which returns a pointer to a  |
 |  Node that contains the article with the given key or NULL     |
 |  if key isn't found; a class Node, which has public members of |
 |  data of type ElementType and a pointer next; Node *deleter(), |
 |  which returns the previous pointer of the node that was being |
 |  searched for and the node that was found gets deleted;        |
 |  NodePointer first, a  pointer to the first node in the        |
 |  linkedlist and; NodePointer predPtr, a pointer initialized to |
 |  first, but increases as necessary.                            |
 |                                                                |
 |  Operations are:                                               |
 |   LinkedList(): a constructor that initializes the empty list  |
 |   insert(): inserts the element into the list in sorted order  |
 |   find(): fills item with the article data found in th list    |
 |   erase(): removes the node with the corresponding key and     |
 |         deallocates its memory.                                |
 |                                                                |
 |  Author: Megan MacDonald                                       |
 |  Date Completed: March 2, 2009                                 |
 |  Class: CSC 2110, section 002                                  |
 |  Tennessee Technological University                            |
 |                                                                |
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <iostream>
#include <string>
using namespace std;

typedef struct Articles ElementType;
typedef std::string KeyType;

//struct which has three elements: key, name, and title
struct Articles
{
	string key;
	string name;
	string title;
};

class LinkedList
{
	private:
		class Node
		{
		public:
			ElementType data;
			Node * next;
			Node(ElementType dataValue){		
				data = dataValue;
				next = NULL;
			}
		};
		typedef Node * NodePointer;
		Node *LinkedList::found(const KeyType &key)
		{
			NodePointer ptr;
			ptr = first;
			ElementType item;
			while (ptr != NULL)
			{
				if (ptr->data.key == key)
				{
					item.key = ptr->data.key;
					item.title = ptr->data.title;
					item.name = ptr->data.name;
					cout << "-----------------------------------------------------------------------------------" << endl;
					cout << "     Key: " << item.key << endl;
					cout << "   Title: " << item.title << endl;
					cout << "  Author: " << item.name << endl;
					cout << "-----------------------------------------------------------------------------------" << endl;
					return ptr;
				}
				else
					ptr = ptr->next;
			}
			if (ptr == NULL)
				return NULL;
		}
		Node *LinkedList::deleter(const KeyType &key)
		{
			NodePointer ptr;
			ptr = first;
			ElementType item;
			while (ptr != NULL)
			{
				if (ptr->data.key == key)
				{
					predPtr->next=ptr->next;
					delete ptr;
					return predPtr;
				}
				else
					ptr = ptr->next;
			}
			if (ptr == NULL)
				return NULL;
		}
		NodePointer first;
		NodePointer predPtr;
	public:
		LinkedList();
		void insert (const ElementType &item);
		bool find (const KeyType &key, ElementType &item);
		bool erase (const KeyType &key);
		void display();
};
		bool operator<(const ElementType &e1, const KeyType &key);
		bool operator>=(const ElementType &e1, const KeyType &key);
/*~~~linkedlist.cpp~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 |    An implementation file for data of type LinkedList. Private |    
 |  members include: Node *found(), which returns a pointer to a  |
 |  Node that contains the article with the given key or NULL     |
 |  if key isn't found; a class Node, which has public members of |
 |  data of type ElementType and a pointer next; Node *deleter(), |
 |  which returns the previous pointer of the node that was being |
 |  searched for and the node that was found gets deleted;        |
 |  NodePointer first, a  pointer to the first node in the        |
 |  linkedlist and; NodePointer predPtr, a pointer initialized to |
 |  first, but increases as necessary.                            |
 |                                                                |
 |  Operations are:                                               |
 |   LinkedList(): a constructor that initializes the empty list  |
 |   insert(): inserts the element into the list in sorted order  |
 |   find(): fills item with the article data found in th list    |
 |   erase(): removes the node with the corresponding key and     |
 |         deallocates its memory.                                |
 |                                                                |
 |  Author: Megan MacDonald                                       |
 |  Date Completed: March 2, 2009                                 |
 |  Class: CSC 2110, section 002                                  |
 |  Tennessee Technological University                            |
 |                                                                |
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <iostream>
#include <iomanip>
using namespace std;
#include "linkedlist.h"

//contructor
LinkedList::LinkedList()
{
	first = NULL;
}

//insert function
void LinkedList::insert(const ElementType &dataValue)
{
	NodePointer nPtr = new Node(dataValue);
	predPtr = first;
	NodePointer afterPtr;
	if (first == NULL)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else if (predPtr->data >= nPtr->data.key)
	{
		nPtr->next = first;
		first = nPtr;
	}
	else
	{
		while (!((predPtr->next == NULL) || (predPtr->next->data >= nPtr->data.key)))
		{
			predPtr=predPtr->next;
		}
		nPtr->next = predPtr->next;
		predPtr->next = nPtr;
	}
}

//find function
bool LinkedList::find(const KeyType &key, ElementType &item)
{
	if (found(key))
	{
		return true;
	}
	else if (!found(key))
		return false;
}

//erase function
bool LinkedList::erase(const KeyType &key)
{
	if (deleter(key))
	{
		return true;
	}
	else if (!deleter(key))
		return false;
}

//display function
void LinkedList::display()
{
	LinkedList::NodePointer ptr;
	ptr = first;
	cout << "--------------------------------------------------------------------------------" << endl;
	cout << " Key                 Author                Title                          " << endl;
	cout << "--------------------------------------------------------------------------------" << endl;
	while (ptr != NULL)
	{
		cout << left << setw(20) << ptr->data.key << " " << setw(20) << ptr->data.name << "  " << setw(40) << ptr->data.title << endl;
		ptr = ptr->next;
	}
}

//overloading ==
bool operator==(const ElementType &e1, const KeyType &key)
{
	if (e1.key == key)
		return true;
	else
		return false;
}

//overloading >=
bool operator>=(const ElementType &e1, const KeyType &key)
{
	if (e1.key >= key)
		return true;
	else
		return false;
}
/*~~~program2.cpp~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 |                                                                     |
 |     A driver file which  reads and manipulates the CACM database.   |
 |  The program incorporates 1 class (with a header and implementation |
 |  file): LinkedList. LinkedList handles the LinkedList(), insert(),  |
 |  find(), erase(), display(), and 2 overload functions. Definition   |
 |  of the functions are in the corresponding .cpp/.h file.            |                                |
 |     Program play consists of reading in a file and placing each     |
 |  line into the data of a struct, Articles s. The program then       |
 |  inserts s into the linkedlist l. Once, the end of file has been    |
 |  reached, the file closes. The menu is then displayed. Depending on |
 |  the charachter entered the associating function is called. If an   |
 |  an invalid character is selected, the user will be prompted to     |
 |  re-enter the character.                                            |
 |                                                                     |
 |  Author: Megan MacDonald                                            |
 |  Date Completed: March 2, 2009                                      |
 |  Class: CSC 2110, section 002                                       |
 |  Tennessee Technological University                                 |
 |                                                                     |
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "linkedlist.h"

void menuDisplay();

int main()
{
	char ch;          //character ch is used for input of the menu choice
	KeyType findKey;  //string used for finding for a Node
	KeyType srchKey;  //string used for searching for a Node
	KeyType addKey;   //string used for adding for a Node
	KeyType eraseKey; //string used for erasing for a Node
	bool menuActive;  //bool statement to keep taking a menu option until false
	
	LinkedList l;     //creates an object of LinkedList, l
	cout << "$ cacmLibrary cacmpub.txt" << endl
	<< "Loading library please wait..." << endl;
	ifstream inFile("cacmpublong.txt");  //opening the file to be used
	Articles s;  //struct used to insert into l
	Articles temp; //temporary struct
	if (inFile.is_open()) //if the file was opened...
	{
		while (!inFile.eof()) //and until the end of the file...
		{
			getline (inFile,s.key);   //read in a line as s.key...
			getline (inFile,s.name);  //read in a line as s.name...
			getline (inFile,s.title); //read in a line as s.title...
			if (s.key >= " ")         //and if the key is not null...
				l.insert(s);          //insert the struct into l
		}
		inFile.close();     //close file
	}
	else  //should the file not open...
	{
		cout << "Unable to open file";  //display an error msg
	}
	
	cout << "Hello! Welcome to the CACM Library." << endl << endl;
	menuDisplay();  //displays the menu
	
	menuActive = true; //initiates menuActive to true
	while (menuActive) //while loop to handle the state of menuActive
	{
		ch = '\0';     //initalizes the ch to null
		cout << "Your Choice:";  //prompts user to enter their choice...
		cin.get(ch);             //stores the character in ch...
		cin.ignore(10,'\n');     //and ignores the enter
		cout << endl;
		
		if (ch == 'f' || ch == 'F')  //if the user enters an F...
			{
				cout << "Please enter a search key:"; //user is prompted for key
				cin >> srchKey;                   //input of the key to search for
				if (l.find(srchKey,temp))         //if the key is found...
				{
					cout << endl;                 //no error.
				}
				else if (!l.find(srchKey,temp))   //if key is not found, then error msg displayed
				{
					cout << "*-------------------------------------------------------*" << endl;
					cout << "|  Sorry, but there are no records matching your query. |" << endl;
					cout << "*-------------------------------------------------------*" << endl << endl;
				}
			}
		else if (ch == 'l' || ch == 'L') //if the user enters an L...
			{
				l.display();            //the linkedlist l is displayed
				cout << endl;
			}
		else if (ch == 'a' || ch == 'A') //if the user enters an A...
			{
				cout << "Enter the key for your new article:"; //user is prompted to enter key
				cin >> addKey;                       //input of key to add
				if (l.find(addKey,s))                //if the key is found...
				{
					cout << "This key already exists!" << endl;  //key will not be added
				}
				else if (!l.find(addKey,s))          //if key is not found...
				{
					s.key = addKey;                  //s.key is the string addKey
					cout << endl << "Enter the author's name:"; //promt to get name
					cin >> s.name;                        //input of name
					cout << endl << "Enter the title of the article:";  //promt to get title
					cin >> s.title;                       //input of title
					l.insert(s);                          //inserts the struct into linkedlist l
						cout << endl;                     //display of what was added
						cout << "*----------------------------------------*" << endl;
						cout << "| The following record has been ADDED    " << endl;
						cout << "|                                        " << endl;
						cout << "|    Key: " << s.key << endl;
						cout << "|  Title: " << s.title << endl;
						cout << "| Author: " << s.name << endl;
						cout << "*----------------------------------------*" << endl;
				}
				cout << endl;
			}
		else if (ch == 'r' || ch == 'R')  //if the user enters an R...
			{
				cout << "Enter the key to remove:";  //user is prompted to enter key
				cin >> eraseKey;                     //input of key to erase
				if (!l.erase(eraseKey))              //if the key is not found, error msg is displayed
				{
					cout << "----------------------------------------------------------------------" << endl;
					cout << "| Sorry, record not removed because it was not found in the database |" << endl;
					cout << "----------------------------------------------------------------------" << endl;
				}
				else                                //if the key is found...
				{
					l.erase(eraseKey);             //the key is erased and displays what was erased.
					cout << "*---------------------------------------------------*" << endl;
					cout << "| The following record has been REMOVED             " << endl;
					cout << "|                                                   " << endl;
					cout << "| Key: " << eraseKey << "                           " << endl;
					cout << "*---------------------------------------------------*" << endl;
				}
				cout << endl;
			}			
		else if (ch == 'e' || ch == 'E')  //if user enters an E...
		{
			cout << "Thank you for using the CACM Library!" << endl << "$" << endl;  //user is thanked...
			menuActive=false; //and the program exits
		}
		else if (ch != 'f' && ch != 'F' && ch != 'a' && ch != 'A' && ch != 'l' && ch != 'L' && ch != 'r' && ch != 'R' &&  ch != 'e' && ch != 'E')
			cout << "Invalid Choice." << endl;  //when an invalid choice is entered, error msg
	}
	return 0;
}

void menuDisplay()  //function displays the output of the menu
{
	cout << "What would you like to do?" << endl << endl;
	
	cout << "*------------------------------*" << endl;
	cout << "| (F)ind an article            |" << endl
		 << "| (L)ist all articles          |" << endl
		 << "| (A)dd a new article          |" << endl
		 << "| (R)emove an existing article |" << endl
		 << "| (E)xit                       |" << endl;
	cout << "*------------------------------*" << endl << endl;
}
Question Answered as of 5 Years Ago by siddhant3s
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article