Final Project: Shop Inventory

Lab C++ Advanced 30 points

Build a small inventory system. Read n commands:

  • add NAME QTY PRICE – add QTY items (adding to an existing product increases its quantity; the price is updated to the new PRICE),
  • sell NAME QTY – sell items; if the product is unknown or there aren't enough, print cannot sell NAME, otherwise add the money to the takings,
  • report – print every product in alphabetical order as NAME QTY.

At the end print Takings: X with 2 decimal places. Use a class with a map inside.

Input

n, then n commands.

Output

The output of the commands, then the takings line.

Example

Input

6
add pen 10 1.50
add book 3 12.00
sell pen 4
sell book 5
sell cup 1
report

Output

cannot sell book
cannot sell cup
book 3
pen 6
Takings: 6.00
Sample input available Sample output available
Editor
C++

Hints

Store a map<string, Product> inside an Inventory class.

Read the command word first, then read the rest depending on which command it is.

Check products.count(name) before selling so you don't create an empty product.

Solution explanation

The class hides the map and the takings, and its methods enforce the rules. The map keeps the report sorted automatically.

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

struct Product {
    int quantity = 0;
    double price = 0;
};

class Inventory {
    map<string, Product> products;
    double takings = 0;
public:
    void add(const string& name, int qty, double price) {
        products[name].quantity += qty;
        products[name].price = price;
    }

    bool sell(const string& name, int qty) {
        if (products.count(name) == 0 || products[name].quantity < qty) {
            return false;
        }
        products[name].quantity -= qty;
        takings += qty * products[name].price;
        return true;
    }

    void report() const {
        for (const auto& [name, p] : products) {
            cout << name << " " << p.quantity << "\n";
        }
    }

    double getTakings() const { return takings; }
};

int main() {
    int n;
    cin >> n;
    Inventory shop;
    for (int i = 0; i < n; i++) {
        string command;
        cin >> command;
        if (command == "add") {
            string name;
            int qty;
            double price;
            cin >> name >> qty >> price;
            shop.add(name, qty, price);
        } else if (command == "sell") {
            string name;
            int qty;
            cin >> name >> qty;
            if (!shop.sell(name, qty)) {
                cout << "cannot sell " << name << "\n";
            }
        } else if (command == "report") {
            shop.report();
        }
    }
    cout << fixed << setprecision(2) << "Takings: " << shop.getTakings() << "\n";
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD