Inventory System

Lab C++ Advanced 30 points

Build an inventory with a class and a map: add NAME QTY PRICE, sell NAME QTY (print insufficient NAME if short or unknown), report (each item sorted by name as NAME QTY @ PRICE with 2 decimals, then value TOTAL).

Input

n, then n commands.

Output

Messages and reports.

Example

Input

6
add pen 10 1.5
add book 2 12
sell pen 4
sell book 3
add pen 5 1.75
report

Output

insufficient book
book 2 @ 12.00
pen 11 @ 1.75
value 43.25
Sample input available Sample output available
Editor
C++

Hints

items_[name] creates a default Item the first time.

Solution explanation

A class that owns a map hides the storage details behind a small, clear interface.

Show solution
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
using namespace std;

class Inventory {
public:
    void add(const string &name, int qty, double price) {
        auto &item = items_[name];
        item.qty += qty;
        item.price = price;
    }
    bool sell(const string &name, int qty) {
        auto it = items_.find(name);
        if (it == items_.end() || it->second.qty < qty) return false;
        it->second.qty -= qty;
        return true;
    }
    void report() const {
        double total = 0;
        for (const auto &[name, item] : items_) {
            cout << name << " " << item.qty << " @ " << item.price << "\n";
            total += item.qty * item.price;
        }
        cout << "value " << total << "\n";
    }

private:
    struct Item {
        int qty = 0;
        double price = 0;
    };
    map<string, Item> items_;
};

int main() {
    Inventory inv;
    int n;
    cin >> n;
    cout << fixed << setprecision(2);
    for (int i = 0; i < n; i++) {
        string cmd;
        cin >> cmd;
        if (cmd == "add") {
            string name;
            int qty;
            double price;
            cin >> name >> qty >> price;
            inv.add(name, qty, price);
        } else if (cmd == "sell") {
            string name;
            int qty;
            cin >> name >> qty;
            if (!inv.sell(name, qty)) cout << "insufficient " << name << "\n";
        } else {
            inv.report();
        }
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD