I get an infinite loop if i enter a char/string during the switch statement, so i made an exception to catch anything other then integers. But, i still get the infinite loop. I may be doing something wrong so any help would be great.
#include <iostream>
#include <string>
#include <conio.h>
#include <exception>
#include <typeinfo>
using namespace std;
class list
{
private:
struct node
{
string data;
node *next;
}*head, *tail;
public:
list() : head(0), tail(0) {}
~list();
void push_front(string &d);
void push_back(string &d);
bool isempty() const;
bool pop_back(string &d);
bool pop_front(string &d);
friend ostream &operator<<(ostream &, list &);
};
list::~list()
{
node *temp = head;
node *tmp;
while(temp != 0)
{
tmp = temp;
temp = temp->next;
delete tmp;
}
}
bool list::isempty() const
{
return head == 0;
}
void list::push_front(string &d)
{
node *temp = new node;
temp->data = d;
temp->next = 0;
if(isempty())
head = tail = temp;
else
{
temp->next = head;
head = temp;
}
}
void list::push_back(string &d)
{
node *temp = new node;
temp->data = d;
temp->next = 0;
if(isempty())
head = tail = temp;
else
{
tail->next = temp;
tail = temp;
}
}
bool list::pop_front(string &d)
{
if(isempty())
return false;
else
{
node *temp = head;
if(head == tail)
head = tail = 0;
else
head = head->next;
d = temp->data;
delete temp;
return true;
}
}
bool list::pop_back(string &d)
{
if(isempty())
return false;
else
{
node *temp = tail;
if(head == tail)
head = tail = 0;
else
{
node *current = head;
while(current->next != tail)
current = current->next;
tail = current;
current->next = 0;
}
d = temp->data;
delete temp;
return true;
}
}
ostream &operator<<(ostream &output, list &L)
{
list::node *temp = L.head;
while(temp != 0)
{
output << temp->data << endl;
temp = temp->next;
}
return output;
}
int main()
{
list LL;
int choice;
string name;
int temp;
try
{
do
{
cout << "Enter choice: " << endl;
cout << "1. Push_front." << endl;
cout << "2. Push_back." << endl;
cout << "3. Pop_front." << endl;
cout << "4. Pop_back." << endl;
cout << "5. Quit." << endl;
cout << "$ ";
cin >> choice;
if(typeid(choice) != typeid(temp)) //here
throw choice;
else
{
switch(choice)
{
case 1:
cout << "Enter name to save" << endl;
cout << "$ ";
getline(cin, name);
getline(cin, name);
LL.push_front(name);
cout << LL;
break;
case 2:
cout << "Enter name to save" << endl;
cout << "$ ";
getline(cin, name);
getline(cin, name);
LL.push_back(name);
cout << LL;
break;
case 3:
LL.pop_front(name);
cout << LL;
break;
case 4:
LL.pop_back(name);
cout << LL;
break;
case 5:
break;
}
}
}while(choice != 5);
}catch(...)
{
cout << endl << endl;
cout << "error... that choice is not on the system." << endl;
_getch();
}
return 0;
}