Question

PLEASE ADD PRICE CHECK IN MY CODE BELOW: ADD THIS: Price check Prompt the user to...

PLEASE ADD PRICE CHECK IN MY CODE BELOW:

ADD THIS:

Price check

Prompt the user to input the SKU number for the item they are looking for.

Search through the inventory and display the cost of the item.

Note that if the item does not exist in the inventory, the program displays an informative message.

MY CODE:

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

// define maximum number of items
const MAX_ITEMS = 10;

//struct to use as asked in problem
struct Item{
int sku_;
float price_;
int quantity_;
};

int main(){
struct Item item[MAX_ITEMS]; // array of item representing the inventory
int size = 0; //number of items in the inventory initially its empty

// temporary variable to store the user input
int tempSku, tempQuantity;
float tempPrice;
printf("\n\t\tWelcome to the Shop\n\t\t===================\n\n");
while(1){
printf("\t\tPlease select from the following options:\n"
"\t\t1) Display the inventory.\n"
"\t\t2) Add to the inventory.\n"
"\t\t0)Exit.\n\t\tSelect: ");
int c; // variable where we store the options
scanf("%d", &c);
switch(c){
case 1:
printf("\n\t\tInventory\n\t\t=========================================\n");
printf("\t\tSku\t\tPrice\t\tQuantity\n\n");
// print the inventory by iterating through item[]
int i;
for(i = 0; i < size; ++i){
printf("\t\t%d\t\t%f\t\t%d\n\n",item[i].sku_, item[i].price_, item[i].quantity_);
}
printf("\t\t=========================================\n\n");
break;
case 2:
printf("\n\t\tPlease input a SKU number: ");
scanf("%d", &tempSku);
printf("\t\tQuantity: ");
scanf("%d",&tempQuantity);
printf("\t\tPrice: ");
scanf("%f", &tempPrice);
if(size >= MAX_ITEMS){
printf("\n\t\tItem can't be added, Inventory is full\n\n");
break;
}

// assign these temporary variable and increase the size of inventory
item[size].sku_ = tempSku;
item[size].quantity_ = tempQuantity;
item[size].price_ = tempPrice;
size++;
printf("\n\t\tItem is successfully added to the inventory\n\n");
break;
case 0:
return 0;
default:
printf("\n\t\tInvalid Input, try again\n\n");

}
}

return 0;
}

MY OUTPUT:

Welcome to the Shop

===================

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:8

Invalid input, try again: Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:2

Please input a SKU number:2341

Quantity:3

Price:12.78

The item is successfully added to the inventory.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:2

Please input a SKU number:4567

Quantity:9

Price:98.2

The item is successfully added to the inventory.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:1

Inventory

=========================================

Sku         Price       Quanity

2341        12.78       3

4567        98.20       9

=========================================

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:2

Please input a SKU number:2341

Quantity:5

The item exists in the repository, quanity is updated.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:1

Inventory

=========================================

Sku         Price       Quanity

2341        12.78       8

4567        98.20       9

=========================================

Please select from the following options:

1) Display the inventory.

2) Add to shop.

0) Exit.

Select:0

Good bye!

OUT PUT AFTER YOU ADD PRICE CHECK:

Welcome to the Shop

===================

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:2

Please input a SKU number:2341

Quantity:4

Price:12.78

The item is successfully added to the inventory.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:2

Please input a SKU number:4567

Quantity:9

Price:98.20

The item is successfully added to the inventory.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:1

Inventory

=========================================

Sku         Price       Quanity

2341        12.78       4

4567        98.20       9

=========================================

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:3

Please input the sku number of the item:

2322

Item does not exist in the shop! Please try again.

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:3

Please input the sku number of the item:

2341

Item 2341 costs $12.78

Please select from the following options:

1) Display the inventory.

2) Add to shop.

3) Price check.

0) Exit.

Select:0

Good bye!

0 0
Add a comment Improve this question Transcribed image text
Answer #1


#define _CRT_SECURE_NO_WARNINGS
#define MAX_INVENTORY_SIZE 10
#define MAX_ITEMS 10
#define TAX .13

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

struct Cart {
   int sku[MAX_ITEMS];
   float price[MAX_ITEMS];
   int quantity[MAX_ITEMS];
   float totalCost;
   int size;
};


void menu();
void clear();
void clearInputBuffer();
int validate(int, int);
void displayInventory(const int sku[], const float price[]);
int searchInventory(const int sku[], const int item);
void checkPrice(const int sku[], const float price[]);
void displayCart(const struct Cart*);
void addCart(struct Cart*, const int[], const float[]);
void removeCart(struct Cart*);
void checkout(const struct Cart*);
int readInventory(const char[], int[], float[]);
void printReceipt(const char[], struct Cart*);


int main() {
   int select = 0;
   int sku[MAX_INVENTORY_SIZE];
   float price[MAX_INVENTORY_SIZE];

   struct Cart myCart; // An object of Cart
   myCart.size = 0; // Number of items in myCart (total = 10)
   myCart.totalCost = 0;

   if (readInventory("inventory.txt", sku, price) == 0) {
       clear();
       printf("Welcome to the Grocery Store\n");
       printf("============================\n");
       while (select != 8) {
           menu();
           printf("Select: ");
           select = validate(1, 8);
           switch (select) {
           case 1:
               displayInventory(sku, price);
               break;
           case 2:
               checkPrice(sku, price);
               break;
           case 3:
               displayCart(&myCart);
               break;
           case 4:
               addCart(&myCart, sku, price);
               break;
           case 5:
               removeCart(&myCart);
               break;
           case 6:
               checkout(&myCart);
               printReceipt("receipt.txt", &myCart);
               break;
           case 7:
               clear();
               break;
           case 8:
               printf("Good bye!\n");
           }
           printf("\n");
       }
   }
   return 0;
}
// Print the menu
//
void menu() {
   printf("Please select from the following options:\n");
   printf("1) Display the inventory.\n");
   printf("2) Price check.\n");
   printf("3) Display my shopping cart.\n");
   printf("4) Add to cart.\n");
   printf("5) Remove from cart.\n");
   printf("6) Check Out.\n");
   printf("7) Clear Screen.\n");
   printf("8) Exit.\n\n");
}

// Print 40 new lines.
//
void clear() {
   int i;
   for (i = 0; i < 40; i++)
       printf("\n");
}

void clearInputBuffer() {
   while (getchar() != '\n')
       ; // empty statement intentional  
}

// Validate and return an input within the range low and high
//
int validate(int low, int high) {
   int value, keeptrying = 1, numberScanned;
   char after;
   do {
       numberScanned = scanf("%d%c", &value, &after);
       if (numberScanned == 0) {
           printf("Invalid Input: ");
           clearInputBuffer();
       }
       else if (after != '\n') {
           printf("Invalid Input: ");
           clearInputBuffer();
       }
       else if (value < low || high < value) {
           printf("Invalid Input: ");
       }
       else
           keeptrying = 0;
   } while (keeptrying == 1);
   return value;
}

// Print the inventory
//
void displayInventory(const int sku[], const float price[]) {
   printf("\nInventory\n");
   printf("=========================================\n");
   printf("Sku         Price\n");
   for (int i = 0; i < MAX_INVENTORY_SIZE; i++)
       printf("%-12d%.2f\n", sku[i], price[i]);
   printf("=========================================\n\n");
}

// Return the index of the item, -1 if not found
//
int searchInventory(const int sku[], const int item) {
   for (int i = 0; i < MAX_INVENTORY_SIZE; i++) {
       if (sku[i] == item)
           return i;
   }
   return -1;
}

// Receive a SKU number from the user and display the cost of the item.
//
void checkPrice(const int sku[], const float price[]) {
   int itemNum, found;
   printf("Please input the sku number of the item:\n");
   itemNum = validate(0, 99999);
   found = searchInventory(sku, itemNum);
   if (found == -1)
       printf("Item does not exist in the shop! Please try again.\n");
   else
       printf("Item %d costs $%.2f.\n", itemNum, price[found]);
}

// Display the each itemNum, quantity, price in the cart
//
void displayCart(const struct Cart* pShoppingCart) {
   printf("\nShopping Cart\n");
   printf("=========================================\n");
   printf("Sku         Quantitiy       Price\n");
   for (int i = 0; i < pShoppingCart->size; i++)
       printf("%-12d%-16d%.2f\n", pShoppingCart->sku[i], pShoppingCart->quantity[i], pShoppingCart->price[i]);
   printf("=========================================\n");
}

// Add item to the cart - increment size by 1 if the item is not in the cart.
// Assume the cart can hold only 200 items(quantity) in total regardless of which item it is.
//
void addCart(struct Cart* pShoppingCart, const int sku[], const float price[]) {
   int itemNum, quantity = 0, already = 0, found = -1;
   do {
       int totalQuantity = 0;
       for (int i = 0; i < pShoppingCart->size; i++)
           totalQuantity += pShoppingCart->quantity[i];
       if (totalQuantity >= 200) {
           printf("Your cart can not hold any more items!\n");
           found = 0;
       }
       else {
           printf("Please input a SKU number: ");
           itemNum = validate(0, 99999);
           found = searchInventory(sku, itemNum);
           if (found == -1)
               printf("Item does not exist in the shop! Please try again.\n");
           else {
               printf("Quantity: ");
               scanf("%d", &quantity);

               if (totalQuantity + quantity > 200) {
                   printf("The number of items a cart can hold is 200.\n");
                   if (200 - totalQuantity > 1)
                       printf("Your cart can hold %d more items!\n\n", 200 - totalQuantity);
                   else if (200 - totalQuantity == 1)
                       printf("Your cart can hold 1 more item!\n\n");
                   found = -1;
               }
               else {
                   for (int i = 0; i < pShoppingCart->size; i++) {
                       if (pShoppingCart->sku[i] == itemNum) {
                           already = 1;
                           pShoppingCart->quantity[i] += quantity;
                           break;
                       }
                   }
                   if (already == 0) {
                       pShoppingCart->sku[pShoppingCart->size] = itemNum;
                       pShoppingCart->quantity[pShoppingCart->size] = quantity;
                       int j = searchInventory(sku, itemNum);
                       pShoppingCart->price[pShoppingCart->size] = price[j];
                       pShoppingCart->size += 1;
                       break;
                   }
                   printf("The item is successfully added to the cart.\n");
               }
           }
       } // end else
   } while (found == -1);
}

// Remove the items in the cart by setting size = 0
//
void removeCart(struct Cart* pShoppingCart) {
   if (pShoppingCart->size == 0) {
       printf("The cart is already empty.\n");
   }
   else {
       pShoppingCart->size = 0;
       pShoppingCart->totalCost = 0;
       printf("The cart is successfully removed!\n");
   }
}

// Calculate the total cost and (print it)
//
void checkout(const struct Cart* pShoppingCart) {
   float sum = 0;
   if (pShoppingCart->size > 0) {
       for (int i = 0; i < pShoppingCart->size; i++) {
               sum += pShoppingCart->price[i] * pShoppingCart->quantity[i];
       }
   }
   //printf("The total price is sum = %.2f\n", sum);
}

// Read inventory information from the file and store it to the corresponding arrays
// Returns 0 if file is read succesfful, -1 otherwise
//
int readInventory(const char filename[], int sku[], float price[]) {
   FILE* file = NULL;
   file = fopen(filename, "r");
   if (file) {
       for (int i = 0; i < MAX_INVENTORY_SIZE && !feof(file); i++) {
           if (fscanf(file, "%d,%f", &sku[i], &price[i]) == 2);
           else i--;
       }
       fclose(file);
       return 0;
   }
   else {
       printf("Failed to open file\n");
       return -1;
   }

}

// Print the shopping cart as well as the total price to the file
//
void printReceipt(const char filename[], struct Cart* pShoppingCart) {
   FILE* file = NULL;
   file = fopen(filename, "w");
   if (file) {
       fprintf(file, "\nShopping Cart\n");
       fprintf(file, "=========================================\n");
       fprintf(file, "Sku         Quantitiy       Price\n");
       for (int i = 0; i < pShoppingCart->size; i++) {
           fprintf(file, "%-12d%-16d%.2f\n", pShoppingCart->sku[i],
               pShoppingCart->quantity[i], pShoppingCart->price[i]);
           pShoppingCart->totalCost += pShoppingCart->price[i] * pShoppingCart->quantity[i];
       }
       fprintf(file, "=========================================\n\n");
       fprintf(file, "The total price is sum = %.2f", pShoppingCart->totalCost);
       fclose(file);
   }
   else {
       printf("Failed to open file\n");
   }
}

inventory.txt

2358,12.60
7654,34.99
1209,5.70
1345,12.50
7809,23.8
1092,10.00
8723,3.23
6654,2.12
5455,14.99
7234,95.99


Add a comment
Know the answer?
Add Answer to:
PLEASE ADD PRICE CHECK IN MY CODE BELOW: ADD THIS: Price check Prompt the user to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Fix the code. Use Valgrind to compile below code with no warning and no memory error....

    Fix the code. Use Valgrind to compile below code with no warning and no memory error. Also give a comment about how you fix the code. gcc -std=c99 -pedantic -Wall -Wextra -ftrapv -ggdb3 $* -o question5 question5.c && ./question5 gcc -std=c99 -pedantic -Wall -Wextra -ftrapv -ggdb3 -fsanitize=address -o question5 question5.c && ./question5 Both of these should get the same output . For example if we input 65535 4 3 2 1 it should give us a output with What is...

  • My question is listed the below please any help this assignment ; There is a skeleton...

    My question is listed the below please any help this assignment ; There is a skeleton code:  copy_file_01.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { char ch ; FILE *source , *target;    if(argc != 3){ printf ("Usage: copy file1 file2"); exit(EXIT_FAILURE); } source = fopen(argv[1], "r"); if (source == NULL) { printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } target = fopen(argv[2], "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch...

  • Please help in C: with the following code, i am getting a random 127 printed in...

    Please help in C: with the following code, i am getting a random 127 printed in front of my reverse display of the array. The file i am pulling (data.txt) is: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 when the reverse prints, it prints: 127 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 not sure why...please...

  • I'm having trouble getting a certain output with my program Here's my output: Please input a...

    I'm having trouble getting a certain output with my program Here's my output: Please input a value in Roman numeral or EXIT or quit: MM MM = 2000 Please input a value in Roman numeral or EXIT or quit: mxvi Illegal Characters. Please input a value in Roman numeral or EXIT or quit: MXVI MXVI = 969 Please input a value in Roman numeral or EXIT or quit: EXIT Illegal Characters. Here's my desired output: Please input a value in...

  • Please, I need help, I cannot figure out how to scan variables in to the function...

    Please, I need help, I cannot figure out how to scan variables in to the function prototypes! ******This is what the program should look like as it runs but I cannot figure out how to successfully build the code to do such.****** My code: #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <conio.h> float computeSeriesResistance(float R1, float R2, float R3); float computeParallelResistance(float R1, float R2, float R3); float computeVoltage(int current, float resistance); void getInputR(float R1, float R2, float R3); void getInputCandR(int...

  • C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. But I need to split this program in three files 1. bill.h = contains the...

    C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. But I need to split this program in three files 1. bill.h = contains the class program with methods and variables 2. bill.cpp = contains the functions from class file 3. main.cpp = contains the main program. Please split this program into three files and make the program run. I have posted the code here. #include<iostream>...

  • I tried to add exception handling to my program so that when the user puts in...

    I tried to add exception handling to my program so that when the user puts in an amount of change that is not the integer data type, the code will catch it and tell them to try again, but my try/catch isnt working. I'm not sure how to fix this problem. JAVA code pls package Chapter9; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUIlab extends JFrame implements ActionListener {    private static final int WIDTH = 300;    private...

  • C++ HELP I need help with this program. I have done and compiled this program in...

    C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. I am using printf and scanf. Instead of printf and scanf use cin and cout to make the program run. after this please split this program in three files 1. bill.h = contains the class program with methods and variables eg of class file class bill { } 2. bill.cpp = contains the functions from class...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • I need a basic program in C to modify my program with the following instructions: Create...

    I need a basic program in C to modify my program with the following instructions: Create a program in C that will: Add an option 4 to your menu for "Play Bingo" -read in a bingo call (e,g, B6, I17, G57, G65) -checks to see if the bingo call read in is valid (i.e., G65 is not valid) -marks all the boards that have the bingo call -checks to see if there is a winner, for our purposes winning means...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT