这是我的主要内容:
int main() {
Inventory Master;
bool flag;
Customer Bob("Bob", "CreditCard.txt");
Customer Joe("Joe", "CreditCard.txt" );
Master.firststock( "inventory.txt" );
vector<Food> temp = Master._Inv;
cout <<"Hi, What would you like to buy today?" << endl;
for(unsigned int i=0; i<temp.size(); i++ ) {
cout << temp[i].name << " " << temp[i].quant << " " << temp[i].price << endl;
}
cout <<"\n";
Food Apple("Apples", .99, 10);
Food Orange("Oranges", .99, 10);
Food Chip("Chips", 3.00, 10);
cout <<"\nHi Bob" << endl;
flag = Bob.addCart(Apple, 7, &Master);
cout <<"Bob's total purchases are Currently: \n";
Bob.report();
flag = Bob.addCart(Orange, 2, &Master);
flag = Bob.addCart(Chip, 2, &Master);
Bob.report();
flag = Bob.removeCart();
Bob.report();
cout <<"Bob, ";
flag = Bob.checkout(&Master);
以下是我实施的以从我的矢量中删除食物_Cart:
bool Customer::removeCart() {
bool flag;
int q = 0;
unsigned int i=0;
string remove;
cout << "\nWhat would you like to remove and how much would you like to remove?" << endl;
cin >> remove >> q;
for (i =0; i < _Cart.size(); i++) {
if(remove == _Cart[i].name) {
if (q >= 0) {
_Cart[i].quant -= q;
//inv->_Inv[i].quant += q;
cout <<"\nYou removed " << q << " " << remove <<" In your cart\n" << endl;
return true;
}
if (q < 0) {
cout << "Invalid number of " << remove << " being removed.\n" << endl;
return true;
}
}
else {
try {
throw remove;
}
catch (string param) {
cout << "\n" << remove << " doesn't exist in your cart\n" << endl;
}
return true;
}
}
我的标题包含函数removeCart:
class Customer {
public:
Customer(string n, string fileName);
~Customer() { _Cart.clear(); };
bool addCart(Food f, int q, Inventory* inv);
bool removeCart();
void report();
bool checkout(Inventory* inv);
protected:
string remove;
string name;
int q;
int card;
double balance;
CreditCard _CC(int card,double balance);
vector<Food> _Cart;
};
现在由于某种原因,当我打电话给removeCart时,输入“苹果”有效,但我注意到我做了一个名为Apple的食物对象,因此不确定为什么键入“苹果”可以用于删除而不是“Apple”。此外,当我尝试“橙色”或“芯片”时,会显示例外情况,但正如您在主要内容中所看到的,我将芯片和橙色添加到Bob的购物车中。我甚至尝试过“橘子”和“筹码”,它仍然让我失去了异常,而不是工作。我很感激你的帮助。
答案 0 :(得分:0)
您的for / if / else结构已损坏。如果您对购物车中的第一个元素不匹配,则会抛出异常,您会立即捕获该异常。尝试更像这样的东西:
for (i =0; i < _Cart.size(); i++)
{
if(remove == _Cart[i].name)
{
if (q >= 0)
{
_Cart[i].quant -= q;
//inv->_Inv[i].quant += q;
cout <<"\nYou removed " << q << " " << remove <<" In your cart\n" << endl;
}
else
cout << "Invalid number of " << remove << " being removed.\n" << endl;
return true;
}
}
cout << "\n" << remove << " doesn't exist in your cart\n" << endl;
return true;
答案 1 :(得分:0)
这是作业吗? :)
首先,“Apple”是你创建的变量的名称,但是你将“Apples”传递给Food的构造函数,所以我想这个值被分配给它的“name”成员,用于比较
其次,正如大卫注意到的那样,只有当您尝试删除购物车中的第一个元素时,您的循环才会起作用。在您的情况下,第一个元素名为“Apples”,因此输入“Apples”可以正常工作。