简体   繁体   English

如何将元素添加到 C 中的结构数组?

[英]How do I add an element to an array of structures in C?

I'm working on a very basic C project, where I need to display a menu and calculate a bill according to what the user has chosen from the menu.我正在做一个非常基本的 C 项目,我需要显示一个菜单并根据用户从菜单中选择的内容计算账单。 For this, I have written the following piece of code为此,我编写了以下代码

struct Food_item
{
    char name[50];
    float price;
};

typedef struct Food_item food;
food french_dishes[4]={{"Champagne",450},{"Pineau",250},{"Monaco",350},{"French Cider",400}};
food order[50];

int choice = -1;
printf("Enter choice: ");
scanf("%d", &choice);

Now I need to add the name of the food and the price of it into my array, order.现在我需要将食物的名称和价格添加到我的数组中,订单。 How do I do this?我该怎么做呢? And if I decide to take multiple orders and add them to my array, order, then how do I do it?如果我决定接受多个订单并将它们添加到我的数组中,订单,那么我该怎么做呢?

When you use the scanf you can instantly save the order in the order variable you already have.当您使用 scanf 时,您可以立即将订单保存在您已有的 order 变量中。 And then by using a simple comparison with the menu you can calculate the final price of the order.然后通过与菜单的简单比较,您可以计算出订单的最终价格。 Also in order to have multiple foods in the same order, you can use a while loop and quit whenever the order is complete.此外,为了在同一订单中有多种食物,您可以使用 while 循环并在订单完成时退出。 *Don't forget to include string.h *不要忘记包含 string.h

printf("The Menu\n");
for(int i=0;i<4;i++)
{
    printf("Food:%s, Price: %.2f\n", french_dishes[i].name, french_dishes[i].price);
}

int end_order = 0;
int count = 0;
while(end_order==0)
{
    printf("Enter Choice(press 'q' to finish order): ");
    scanf("%s", order[count].name);
    if(*order[count].name == 'q')
    {
        end_order = 1;
    }
    else 
    {
        count++;
    }
}

float final_price = 0;
printf("The Order\n");
for(int j=0;j<count;j++)
{
    printf("Food:%s\n", order[j].name);
    for(int i=0;i<4;i++)
    {
        if(strcmp(order[j].name,french_dishes[i].name) == 0)
        {
            final_price = final_price + french_dishes[i].price;
        }
    }
}

printf("Final Price: %.2f\n", final_price);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM