I wrote a couple functions for a school project, and I have them working but I don’t understand why. they should be identical but they only work if one checks current->link and the other checks current itself. Shouldn’t both loops be current != NULL?
The two functions are called in main like so:
customerHead = fillCart(limit, lowLevelInv); //fills linked list
totCart(customerHead, lowLevelInv);
printCart(customerHead, lowLevelInv);
This one only works if the while loop checks current != NULL
int totCart(OrderPtr head, inventory lowLevelInv[])
{
OrderPtr current;
current = head;
int tot = 0;
while(current != NULL)
{
tot += lowLevelInv[current->itemID].cost*current->qtyReceived;
current = current->link;
}
cout<<"Cart total is: "<<tot<<endl;
return tot;
}
This one only works if the while loop checks current->link !=NULL
void printCart(OrderPtr head, inventory lowLevelInv[])
{
OrderPtr current;
current = head;
cout<<"you have ordered: \n";
while(current->link != NULL);
{
cout<<current->orderID<<": "<<current->qtyReceived<<" " <<lowLevelInv[current->itemID].name<<" for "<<lowLevelInv[current->itemID].cost*current->qtyReceived<<endl;
current = current->link;
}
}
Looks like the problem is here:
If you look very carefully, you have a spurious semicolon after the controlling statement in the “while” statement. That means that your program will hang if current->link is ever not null, since nothing ever changes current or current->link.
If that’s not actually your problem (because of a copy pasta problem, for example) you should show us how you’re building your list and what you specifically mean by “doesn’t work”.