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



我正在做一个非常基本的C项目,我需要显示一个菜单,并根据用户从菜单中选择的内容计算账单。为此,我编写了以下代码

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);

现在我需要将食物的名称和价格添加到数组order中。我该怎么做呢?如果我决定取多个order并将它们添加到数组order中,那么我该怎么做呢?

当您使用scanf时,您可以立即将订单保存在您已经拥有的订单变量中。然后,通过与菜单进行简单的比较,您可以计算出订单的最终价格。此外,为了在同一顺序中有多个食物,您可以使用while循环并在订单完成时退出。*不要忘记包含string.h

printf("The Menun");
for(int i=0;i<4;i++)
{
printf("Food:%s, Price: %.2fn", 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 Ordern");
for(int j=0;j<count;j++)
{
printf("Food:%sn", 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: %.2fn", final_price);

最新更新