-
Linked List Problems
Tuesday of this past week I decided I would give myself a long over due refresher course in C++. So I started with the tutorials and when I got to Linked Lists I got stuck and a practice program I was writing.
Code:
#include <iostream>
using namespace std;
struct node
{
char *Inv;
node *pNext;
node *pPrev;
};
node *pHead;
node *pTail;
void AddNode( node *pNode);
int main()
{
char *temp;
node *list;
while (temp != "done")
{
cout<<"Enter inventory item: ";
cin>>temp;
cin.ignore();
list = new node;
list->Inv=temp;
AddNode(list);
}
cout<<"\n\n\n...Ready to print inventory\n\n";
for (list = pHead;list != NULL;list = list->pNext)
{
cout<<list->Inv;
}
}
void AddNode( node *pNode)
{
if ( pHead == NULL )
{
pHead = pNode;
pNode->pPrev = NULL;
}
else
{
pTail->pNext = pNode;
pNode->pPrev = pTail;
}
pTail = pNode;
pNode->pNext = NULL;
}
The program compiles and runs, but when I type the word done in it doesn't continue on to printing out the list it asks for another inventory item.
Any ideas?
-
You can't compare c-strings this way, use strcmp() or use c++ strings as defined in <string>
-
Oops! hehe thanks for the info I'll try that when I get home.
-
Using C++ strings will solve your problems, but if you decide to stick with the C style strings you have to make room for the string. As you have it, temp is a pointer that points off to some random location. You need to allocate space for your character array before you use it. If you use the string class then you wouldn't have to worry about that.
-
Yeah I changed the char to string, too away the * and added #include <string> and it worked! ^_^
I ust needed to add in an IF statement so that the word 'done' wasn't added to the list.
Thanks for all your help guys!!