Доступ к результату цикла для экземпляра класса для вывода - PullRequest
0 голосов
/ 26 октября 2019

Хорошо, поэтому у меня есть назначение инвентаря класса для моего класса C ++. То, с чем я сейчас борюсь, это часть между циклом и созданием объекта.

string description = "";
int id_number{0};
int quantity_number{0};
double price_value{0};

for (int count{1}; count <= inventory_num; count++)
{
    cout << endl;
    cout << "Item #" << count++ << endl;
    cout << "Enter the id number: ";
    cin >> id_number;
    cout << "Descriptiom: ";
    cin.get();
    getline(cin, description);
    cout << "Quantity on hand: ";
    cin >> quantity_number;
    cout << "Unit price: ";
    cin >> price_value;
    cout << endl;

}

InventoryItem item1(id_number, description, quantity_number, price_value);
InventoryItem item2(id_number, description, quantity_number, price_value);
InventoryItem item3(id_number, description, quantity_number, price_value);
InventoryItem item4(id_number, description, quantity_number, price_value);


item1.display(); cout << endl; 
item2.display(); cout << endl;      
item3.display(); cout << endl;
item4.display(); cout << endl;

return EXIT_SUCCESS;
}

Таким образом, проблема, например, заключается в том, что вход зацикливается 4 раза, но на выходе отображаются только данные из ПОСЛЕДНЕГО ВХОДА ЦЕПИ для ВСЕГО ВЫХОДА (item1,item2,item3,item4). Как исправить это парни?

1 Ответ

0 голосов
/ 26 октября 2019

Вы перезаписываете значения в каждой итерации цикла. После цикла значения последней итерации сохраняются в ваших переменных. Вы можете исправить это с помощью std :: vector

#include "InventoryItem.hpp"
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::getline;

int main() {
    string description = "";
    int id_number{0};
    int quantity_number{0};
    double price_value{0};
    std::vector<InventoryItem> items;
    for (int count{1}; count <= inventory_num; count++)
    {
        cout << endl;
        cout << "Item #" << count++ << endl;
        cout << "Enter the id number: ";
        cin >> id_number;
        cout << "Descriptiom: ";
        cin.get();
        getline(cin, description);
        cout << "Quantity on hand: ";
        cin >> quantity_number;
        cout << "Unit price: ";
        cin >> price_value;
        cout << endl;
        items.emplace_back(id_number, description, quantity_number, price_value);
    }

    items[0].display(); cout << endl; 
    items[1].display(); cout << endl;      
    items[2].display(); cout << endl;
    items[3].display(); cout << endl;

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