写一个库存管理系统的代码 C语言
时间: 2024-04-28 21:22:09 浏览: 79
好的,下面是一个简单的库存管理系统的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[50];
float price;
int quantity;
} Product;
typedef struct {
Product *products;
int size;
} Inventory;
void add_product(Inventory *inventory, int id, char *name, float price, int quantity) {
// Allocate memory for new product
Product *new_product = (Product *) malloc(sizeof(Product));
// Set the attributes of the new product
new_product->id = id;
strcpy(new_product->name, name);
new_product->price = price;
new_product->quantity = quantity;
// Add the new product to the inventory
inventory->products = (Product *) realloc(inventory->products, (inventory->size + 1) * sizeof(Product));
inventory->products[inventory->size] = *new_product;
inventory->size++;
// Free the memory used by the new product
free(new_product);
}
int remove_product(Inventory *inventory, int id) {
int i, j;
for (i = 0; i < inventory->size; i++) {
if (inventory->products[i].id == id) {
// Shift all products after the removed product one index to the left
for (j = i; j < inventory->size - 1; j++) {
inventory->products[j] = inventory->products[j + 1];
}
// Resize the inventory to remove the last product
inventory->size--;
inventory->products = (Product *) realloc(inventory->products, inventory->size * sizeof(Product));
return 1;
}
}
return 0;
}
int update_product_quantity(Inventory *inventory, int id, int quantity) {
int i;
for (i = 0; i < inventory->size; i++) {
if (inventory->products[i].id == id) {
inventory->products[i].quantity = quantity;
return 1;
}
}
return 0;
}
Product *get_product(Inventory *inventory, int id) {
int i;
for (i = 0; i < inventory->size; i++) {
if (inventory->products[i].id == id) {
return &inventory->products[i];
}
}
return NULL;
}
void display_inventory(Inventory *inventory) {
int i;
printf("ID\tName\tPrice\tQuantity\n");
for (i = 0; i < inventory->size; i++) {
printf("%d\t%s\t%.2f\t%d\n", inventory->products[i].id, inventory->products[i].name, inventory->products[i].price, inventory->products[i].quantity);
}
}
int main() {
Inventory inventory = { NULL, 0 };
// Add some products to the inventory
add_product(&inventory, 1, "Apple", 1.99, 100);
add_product(&inventory, 2, "Banana", 0.99, 50);
// Display the inventory
display_inventory(&inventory);
// Update the quantity of the first product and remove the second product
update_product_quantity(&inventory, 1, 50);
remove_product(&inventory, 2);
// Display the inventory again
display_inventory(&inventory);
// Free the memory used by the inventory
free(inventory.products);
return 0;
}
```
这个系统包含了两个结构体,一个是 `Product` 结构体用于表示单个产品,另一个是 `Inventory` 结构体用于管理产品库存。
`Inventory` 结构体包含了添加、删除、更新和获取产品的函数。在这个示例中,我们创建了一个 `Inventory` 实例,并向里面添加了两个产品,并展示了整个库存。接着我们更新了第一个产品的库存数量,删除了第二个产品,再次展示了整个库存。
这个示例中使用了动态内存分配来管理产品和库存的数据结构,使用 `malloc()` 和 `realloc()` 函数来分配和重新分配内存,使用 `free()` 函数来释放内存。
阅读全文