cppintermediate30 minutes

Inventory Management System for a Small Store

Build a simple inventory management mini-project in C++ to track products, stock levels, and sales transactions with multi-step logic and data structures.

Challenge prompt

Create a C++ program that models an inventory system for a small store. The program should allow adding new products, updating stock quantities, and processing sales by reducing the stock accordingly. Additionally, implement a function to display all products with their current stock, and another to display all sales transactions recorded. Use appropriate data structures to store products and sales, ensuring efficient updates and queries.

Guidance

  • Define a Product struct or class with fields for product ID, name, and stock quantity.
  • Use a map or unordered_map to store products keyed by product ID for quick access.
  • Maintain a separate vector or list to log sales transactions, storing product ID, quantity sold, and sale timestamp.
  • Implement functions for adding/updating products, processing sales (with stock validation), and displaying the inventory and transaction log.

Hints

  • Use standard library containers like std::unordered_map for product storage to allow O(1) average lookup.
  • Before processing a sale, check if enough stock is available; if not, prevent the sale.
  • For sale timestamps, you can use a simple integer or a string representing date/time, no need for complex time functions.

Starter code

#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>

struct Product {
    int id;
    std::string name;
    int stock;
};

struct Sale {
    int productId;
    int quantity;
    std::string timestamp;
};

class Inventory {
private:
    std::unordered_map<int, Product> products;
    std::vector<Sale> salesLog;

public:
    // Implement methods here
    void addOrUpdateProduct(int id, const std::string &name, int quantity);
    bool processSale(int id, int quantity, const std::string &timestamp);
    void displayProducts() const;
    void displaySalesLog() const;
};

int main() {
    Inventory store;
    // Add sample usage here
    return 0;
}

Expected output

Displays the list of products with current stock and logs of sales transactions as processed, e.g.: Product ID: 1, Name: Apple, Stock: 50 Product ID: 2, Name: Orange, Stock: 30 Sales Log: Product ID: 1, Quantity Sold: 5, Timestamp: 2024-06-10 10:00 Product ID: 2, Quantity Sold: 3, Timestamp: 2024-06-10 11:00

Core concepts

classes and structsunordered_map usagevector and list managementmulti-step logic

Challenge a Friend

Send this duel to someone else and see if they can solve it.