引言

超市购物清单是日常生活中常见的工具,帮助我们有序地管理购物需求,避免遗漏重要物品。C语言作为一种功能强大、应用广泛的编程语言,非常适合用来实现这样的工具。本文将详细讲解如何使用C语言编写一个简单的超市购物清单程序。

程序设计

1. 需求分析

首先,我们需要明确程序的基本功能:

  • 存储商品名称
  • 存储商品数量
  • 添加商品
  • 删除商品
  • 显示当前购物清单

2. 数据结构

为了存储商品信息,我们可以定义一个结构体Product来表示商品,其中包含商品名称和数量。

typedef struct {
    char name[50];
    int quantity;
} Product;

3. 函数设计

接下来,设计以下函数来实现购物清单的功能:

  • void addProduct(Product **products, int *size, char *name, int quantity): 添加商品
  • void deleteProduct(Product **products, int *size, char *name): 删除商品
  • void displayProducts(const Product *products, int size): 显示购物清单

4. 主函数

在主函数中,我们创建一个Product数组来存储商品信息,并调用上述函数来实现程序的主要功能。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[50];
    int quantity;
} Product;

void addProduct(Product **products, int *size, char *name, int quantity) {
    // 动态扩展数组大小
    *products = realloc(*products, (*size + 1) * sizeof(Product));
    (*products)[*size].quantity = quantity;
    strncpy((*products)[*size].name, name, sizeof((*products)[*size].name));
    (*size)++;
}

void deleteProduct(Product **products, int *size, char *name) {
    int i, j;
    for (i = 0; i < *size; i++) {
        if (strcmp((*products)[i].name, name) == 0) {
            for (j = i; j < *size - 1; j++) {
                (*products)[j] = (*products)[j + 1];
            }
            (*products) = realloc(*products, (*size - 1) * sizeof(Product));
            (*size)--;
            break;
        }
    }
}

void displayProducts(const Product *products, int size) {
    int i;
    printf("购物清单:\n");
    for (i = 0; i < size; i++) {
        printf("%s x %d\n", products[i].name, products[i].quantity);
    }
}

int main() {
    Product *products = NULL;
    int size = 0;
    char name[50];
    int quantity;

    while (1) {
        printf("请选择操作:1.添加商品 2.删除商品 3.显示购物清单 4.退出\n");
        int choice;
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("输入商品名称:");
                scanf("%s", name);
                printf("输入商品数量:");
                scanf("%d", &quantity);
                addProduct(&products, &size, name, quantity);
                break;
            case 2:
                printf("输入要删除的商品名称:");
                scanf("%s", name);
                deleteProduct(&products, &size, name);
                break;
            case 3:
                displayProducts(products, size);
                break;
            case 4:
                free(products);
                return 0;
            default:
                printf("无效的操作\n");
        }
    }

    return 0;
}

总结

通过以上步骤,我们成功地使用C语言实现了一个简单的超市购物清单程序。这个程序可以帮助用户方便地管理购物需求,提高购物效率。在实际应用中,可以根据需要进一步完善程序的功能,例如增加商品价格计算、生成购物小票等。