Generation

generate functionSat, 30 Nov 2024

#include <iostream> #include <fstream> #include <string> using namespace std; struct Product { int id; string name; int quantity; }; class Inventory { private: Product* products; int size; int capacity; public: Inventory(int cap = 10) : size(0), capacity(cap) { products = new Product[capacity]; } ~Inventory() { delete[] products; } void addProduct(int id, const string& name, int quantity) { if (size >= capacity) { cout << "Inventory is full! Cannot add more products." << endl; return; } products[size++] = {id, name, quantity}; cout << "Product added successfully!" << endl; } void removeProduct(int id) { int index = -1; for (int i = 0; i < size; ++i) { if (products[i].id == id) { index = i; break; } } if (index == -1) { cout << "Product not found!" << endl; return; } for (int i = index; i < size - 1; ++i) { products[i] = products[i + 1]; } --size; cout << "Product removed successfully!" << endl; } void updateStock(int id, int quantity) { for (int i = 0; i < size; ++i) { if (products[i].id == id) { products[i].quantity = quantity; cout << "Stock updated successfully!" << endl; return; } } cout << "Product not found!" << endl; } void saveToFile(const string& filename) { ofstream file(filename); if (!file) { cout << "Error opening file!" << endl; return; } for (int i = 0; i < size; ++i) { file << products[i].id << " " << products[i].name << " " << products[i].quantity << endl; } file.close(); cout << "Inventory saved to file successfully!" << endl; } void loadFromFile(const string& filename) { ifstream file(filename); if (!file) { cout << "Error opening file!" << endl; return; } size = 0; while (file >> products[size].id >> products[size].name >> products[size].quantity) { ++size; } file.close(); cout << "Inventory loaded from file successfully!" << endl; } void display() const { if (size == 0) { cout << "Inventory is empty!" << endl; return; } cout << "ID\tName\tQuantity" << endl; for (int i = 0; i < size; ++i) { cout << products[i].id << "\t" << products[i].name << "\t" << products[i].quantity << endl; } } }; int main() { Inventory inventory; inventory.addProduct(1, "Mandazi", 400); inventory.addProduct(2, "Parachichi", 50); inventory.addProduct(3, "Machungwa",100); inventory.addProduct(4, "Maembe" , 210); inventory.updateStock(1, 450); inventory.removeProduct(3); inventory.saveToFile("inventory.txt"); inventory.display(); inventory.loadFromFile("inventory.txt"); inventory.display(); return 0; }

Please keep input under 1000 characters

Questions about programming?Chat with your personal AI assistant