Я делаю простую программу корзины покупок, которая выводит стоимость товаров в зависимости от стоимости и количества. После компиляции программа успешно работала, однако, когда я добрался до пункта 2, она пропустила ввод имени элемента и сразу перешла к его стоимости. Вдобавок, когда я вывел то, что было доступно, я получил много бессмысленных значений вместо реальной стоимости всей корзины покупок. Я попытался полностью исключить Item2, но на выходе все равно получил значения мусора. Это мой код. ItemToPurchase. cpp
#include "ItemToPurchase.h"
ItemToPurchase::ItemToPurchase() {
string itemName = "none";
int itemPrice = 0;
int itemQuantity = 0;
}
string ItemToPurchase::GetName() {
return itemName;
}
int ItemToPurchase::GetPrice() {
return itemPrice;
}
int ItemToPurchase::GetQuantity() {
return itemQuantity;
}
void ItemToPurchase::SetName(const char *itemName) {
this->itemName = itemName;
}
void ItemToPurchase::SetPrice(int itemPrice) {
this->itemPrice = itemPrice;
}
void ItemToPurchase::SetQuantity(int itemQuantity) {
this->itemQuantity = itemQuantity;
}
main. cpp
#include "ItemToPurchase.h"
int main(int argc, char const *argv[]) {
ItemToPurchase Item1;
ItemToPurchase Item2;
string item1name;
int item1price;
int item1quantity;
string item2name;
int item2price;
int item2quantity;
cout << "Item 1" << endl;
cout << "Enter the item name: ";
getline(cin, item1name);
item1name = Item1.GetName();
Item1.SetName(item1name.c_str());
cout << "Enter the item price: ";
cin >> item1price;
item1price = Item1.GetPrice();
Item1.SetPrice(item1price);
cout << "Enter the item quantity: ";
cin >> item1quantity;
item1quantity = Item1.GetQuantity();
Item1.SetQuantity(item1quantity);
cout << "Item 2" << endl;
cout << "Enter the item name: ";
getline(cin, item2name);
item2name = Item2.GetName();
Item2.SetName(item2name.c_str());
cout << "Enter the item price: ";
cin >> item2price;
item2price = Item2.GetPrice();
Item2.SetPrice(item2price);
cout << "Enter the item quantity: ";
cin >> item2quantity;
item2quantity = Item2.GetQuantity();
Item2.SetQuantity(item2quantity);
cout << "TOTAL COST" << endl;
cout << item1name << item1quantity << "@ " << "$" << item1price << "= " << "$" << item1price * item1quantity << endl;
cout << item2name << item2quantity << "@ " << "$" << item2price << "= " << "$" << item2price * item2quantity << endl;
cout << "TOTAL: " << "$" << (item1price * item1quantity) + (item2price * item2quantity) << endl;
return 0;
}
И это результат моего терминала
PS C:\Users\chine\OneDrive\Documents\LAB 5#1> ./main.exe
Item 1
Enter the item name: Chocolate Chip Cookies
Enter the item price: 13
Enter the item quantity: 1
Item 2
Enter the item name: Enter the item price: 3 <- Item name was skipped here
Enter the item quantity: 4
TOTAL COST
0@ $4199120= $0
6422268@ $1994867484= $-304621680
TOTAL: $-304621680