It's clear what you're trying to do with the function, but the interaction between the UpdateQuantity function and the class needs to be reworked. It may be helpful to post your class declaration for ShoppingCart so that we can see other functions the class provides.
1) In order to update an item's quantity, you need a function that finds the item. This should be it's own function rather than part of UpdateQuantity(). Once find works, UpdateQuantity() can call find and update the data structure used to store item counts.
2) I recommend removing the lines to gather user input outside of the function (and probably the class) altogether. Your main() or another function should get user input, and then pass that input to ShoppingCart::UpdateQuantity(string itemName, int itemQuantity) as parameters.
3) Most likely, UpdateQuantity() should not call itself.
Following the above recommendations basically guts the code you have, but will put you in a better position to get the function working.
Here's a super brief example of how it could look. FYI, I don't know how you store your items and quantities in ShoppingCart, so I'm going to pretend that you store item names and quantities in two matching vectors of equal length and positions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class ShoppingCart {
public:
void UpdateQuantity(string itemName, int itemQuantity);
...
private:
int FindItem(string itemName);
vector<string> allItemNames;
vector<int> allItemCounts;
const int ITEM_NOT_FOUND = -1;
...
};
// returns index location of itemName or ITEM_NOT_FOUND
int ShoppingChart::FindItem(string itemName)
{
int index = ITEM_NOT_FOUND; // assume item is not found to begin
for (int i = 0; i < allItemNames.size(); i++)
{
if (itemName == allItemNames[i]) // item was found
index = i; // remember the vector index
}
return index;
}
// changes the quantity of an item if found in cart
void ShoppingCart::UpdateQuantity(string itemName, int itemQuantity)
{
int index = FindItem(itemName); // get index of item
if (index == ITEM_NOT_FOUND)
cout << "Item not found in cart." << endl;
else {
allItemCounts[index] = itemQuantity; // update count
cout << "Updated quanity of " << itemName << " to " << itemQuantity << endl;
}
}
|
That's only a simple skeleton and may not be compatible with they way your ShoppingCart class stores it's data members, but hopefully it's easy to understand and gets you thinking in the right direction.
Remember that the goal of most functions is to be simple and to do one thing. It's easy to write giant functions when you're unsure which puzzle pieces you need and how they connect together, but it's better to have more pieces that are small and manageable than fewer big and messy ones.
Good luck!