Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

How can I modify my code (see below), so if the same item is added twice (or more) I want the program to update the

How can I modify my code (see below), so if the same item is added twice (or more) I want the program to update the amount of the already existing item?

right now it looks like this when I add items to the list (I'm using a for-loop (marked in bold cases) to update the amount but it isn't working) :

You list contains 3 items!

1.apples 2 st

2. milk 3 liters

3.apples 4 st

My code:

#define _CRT_SECURE_NO_WARNINGS #include"ShoppingList.h" #include #include // For malloc() and free() #include #include

void addItem(struct ShoppingList *list) { printf("=============================== "); printf("Your list contains %d items ", list->length); list->length++; struct GroceryList* newLength = (struct GroceryItem*)realloc(list->itemList, sizeof(struct GroceryItem) * list->length);

if (newLength == NULL) { printf("Error"); } else { list->itemList = newLength;

while (getchar() != ' '); printf("Enter name: "); gets(list->itemList[list->length - 1].productName);//minus 1 fr att hamna p rtt plats

//incase the same item is added twice or more, update the amount for (int i = 0; i< list->length-1; i++) { if (strcmp(list->itemList[i].productName, list->itemList[list->length - 1].productName) == 0) { list->itemList[i].amount += list->itemList[list->length - 1].amount;

} }

printf("Enter amount: "); scanf_s("%f", &list->itemList[list->length-1].amount);

while (getchar() != ' '); printf("Enter unit: "); gets(list->itemList[list->length - 1].unit); }

printf("The list now contains %d items ", list->length);

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions