Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <string>
using namespace std;
struct Product
{
string Name;
};
struct Inventory
{
Product* Products;
int Count;
};
void InitInventory(Inventory* inventory)
{
inventory->Products = NULL;
inventory->Count = 0;
}
void AddProduct(Inventory* inventory, Product product)
{
if (inventory->Products == NULL)
{
inventory->Products = new Product[1];
inventory->Products[0] = product;
inventory->Count = 1;
}
else
{
Product* temp = inventory->Products;
inventory->Products = new Product[inventory->Count + 1];
for (unsigned int i = 0; i < inventory->Count; i++)
{
inventory->Products[i] = temp[i];
}
inventory->Products[inventory->Count] = product;
inventory->Count++;
delete [] temp;
}
}
void DestroyInventory(Inventory* inventory)
{
if (inventory->Products == NULL)
return;
delete [] inventory->Products;
inventory->Products = NULL;
inventory->Count = 0;
}
int main()
{
Inventory inventory;
InitInventory(&inventory);
while (true)
{
cout << "Enter a product name or '' to exit: ";
Product product;
getline(cin, product.Name);
if (product.Name == "")
break;
AddProduct(&inventory, product);
}
for (unsigned int i = 0; i < inventory.Count; i++)
{
cout << "[" << i << "] - " << inventory.Products[i].Name << "\n";
}
DestroyInventory(&inventory);
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.