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. 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?
CodePudding user response:
When you use the scanf you can instantly save the order in the order variable you already have. 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. *Don't forget to include 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);