Пропуск ввода и вывод значений гаража - PullRequest
0 голосов
/ 16 июня 2020

Я делаю простую программу корзины покупок, которая выводит стоимость товаров в зависимости от стоимости и количества. После компиляции программа успешно работала, однако, когда я добрался до пункта 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

1 Ответ

1 голос
/ 16 июня 2020

есть 2 проблемы:

1 : я думаю, вы сделали отступ, чтобы присвоить некоторые значения по умолчанию переменным-членам ItemToPurchase в конструкторе. Но вы присвоили его локальным переменным. Чтобы назначить его переменным-членам объекта, вы не должны использовать идентификатор типа:

ItemToPurchase::ItemToPurchase() {
  itemName = "none"; 
  itemPrice = 0; 
  itemQuantity = 0;
}

В общем случае рекомендуется использовать некоторый суффикс или префикс, чтобы отличать переменные-члены guish от других переменные: например: m_itemName или itemName_.

2 : этот фрагмент

    cout << "Enter the item price: ";
    cin >> item2price; 

    item2price = Item2.GetPrice();
    Item2.SetPrice(item2price); 

фактически не имеет никакого эффекта. Вы никогда не используете значение, считанное из stdin, когда вы перезаписываете item2Price членом объекта (который не имеет значения по умолчанию) в этом операторе item2price = Item2.GetPrice();. Удалите эту строку (и аналогичные строки в других фрагментах), чтобы она заработала.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...