I am trying to create an online shopping cart. I created a function called RemoveItem in a class called ShoppingCart. What I need the function to do is to remove an element if it matches what the user entered. For example, if the user enters 'apples' it checks the vector to see if there is a match, if there is it removes it. If not it prints that the item is not found. The problem I am having is that it does not allow me to enter the user input and instead print out item is not found.
ShoppingCart.h (RemoveItem() declaration)
using namespace std;
class ShoppingCart {
public:
ShoppingCart();
ShoppingCart(string, string);
string GetCustomerName() const;
string GetDate() const;
int GetNumItemsInCart();
double GetCostofCart(int);
void AddItem(ItemToPurchase);
void RemoveItem(string);
void ModifyItem(string, int);
void Discount();
void PrintTotal();
string PrintDescriptions();
private:
string customerName;
string currentDate;
vector< ItemToPurchase > cartItems;
};
ShoppingCart.cpp (RemoveItem Function)
void ShoppingCart::RemoveItem(string name) {
for (int i = 0; i < cartItems.size(); i++) {
if (cartItems.at(i).GetName() == name) {
cartItems.erase(cartItems.begin(), cartItems.end() + i);
}
if (cartItems.at(i).GetName() != name) {
cout << "Item not found in cart. Nothing removed." << endl;
}
}
}
ItemToPurschase.h (GetName() declaration)
class ItemToPurchase {
public:
ItemToPurchase();
ItemToPurchase(string name, string description, double price, int quantity);
void SetName(string name);
string GetName();
void SetPrice(double price);
double GetPrice();
void SetQuantity(int quantity);
int GetQuantity();
void SetDescription(string description);
string GetDescription();
void PrintItemCost();
void PrintItemDescription();
private:
string itemName;
string itemDesciption;
double itemPrice;
int itemQuantity;
};
#endif ItemToPurchase_H
ItemToPurchase (GetName() function)
string ItemToPurchase::GetName() {
return itemName;
}
Main.cpp (RemoveProduct function)
void RemoveProduct(ShoppingCart& cart) {
string name;
cout << endl;
cout << "REMOVE ITEM FROM CART" << endl;
cout << endl;
cout << "Enter name of item to remove: " << endl;
getline(cin, name);
cart.RemoveItem(name);
cout << endl;
}
do-while loop based on user choice
do {
cout << "MENU" << endl;
cout << "a - Add item to cart" << endl;
cout << "d - Remove item from cart" << endl;
cout << "c - Change item quantity" << endl;
cout << "i - Ouput items' descriptions" << endl;
cout << "o - Output shopping cart" << endl;
cout << "n - Number of items' in cart" << endl;
cout << "q - Quit" << endl;
cout << "Enter selection: " << endl;
cin >> userChoice;
cout << endl;
if (userChoice == 'a') {
AddItem(cart);
}
else if (userChoice == 'd') {
RemoveProduct(cart);
}