Сбой компиляции корзины покупок - PullRequest
0 голосов
/ 26 марта 2020

На данный момент этот код компилирует 10 из 14 тестов, но те, которые не компилируются, не из-за странной ошибки компиляции. Я создаю онлайн-корзину для своего класса C / C ++ (это C) и у меня есть 5 отдельных файлов, но я добавлю сюда только 3, чтобы сэкономить время (main. c, ShoppingCart. c , ItemPurchase. c). Вот мой код:

Это ShoppingCart. c


#include <string.h>

#include <stdio.h>

// definition of the function AddItem()

//Adds an item to cartItems array.

//Has parameters ItemToPurchase and ShoppingCart. Returns ShoppingCart object.

ShoppingCart AddItem(struct ItemToPurchase item, ShoppingCart cart) {

 cart.cartItems[cart.cartSize] = item;

 cart.cartSize = cart.cartSize + 1;

 return cart;

}

// definition of the function RemoveItem()

//Removes item from cartItems array

//Has a char and a ShoppingCart parameter. Returns ShoppingCart object.

ShoppingCart RemoveItem(char name[], ShoppingCart cart) {

 int i = 0;

 char itemFound = 'n';

 for (i = 0; i < cart.cartSize; ++i) {

   if (strcmp(name, cart.cartItems[i].itemName) == 0) {

     itemFound = 'y';

     for (int j = i; j < cart.cartSize; ++j) {

       cart.cartItems[j] = cart.cartItems[j + 1];

     }

   }

 }

 if (itemFound == 'y') {

   cart.cartSize = cart.cartSize - 1;

 }

 //If item name cannot be found, output this message:

 if (itemFound == 'n') {

   printf("Item not found in cart. Nothing removed.\n");

 }

 return cart;

}

// definition of the function ModifyItem()

// Modifies an item's description, price, and/or quantity.

// Has parameters ItemToPurchase and ShoppingCart. Returns ShoppingCart object.

ShoppingCart ModifyItem(char item[50], ShoppingCart cart) {

 int quantity;

 int itemFound = 0;

 printf("Enter the new quantity:\n");

 scanf("%d", & quantity);

 int i = 0;

 for (i = 0; i < cart.cartSize; ++i) {

   if (strcmp(item, cart.cartItems[i].itemName) == 0) {

     itemFound = 1;

     cart.cartItems[i].itemQuantity = quantity;

   }

 }

 if (itemFound == 0) {

   printf("Item not found in cart. Nothing modified.\n");

 }

 return cart;

}

// definition of the function GetNumItemsInCart()

// Returns quantity of all items in cart. Has a ShoppingCart parameter

int GetNumItemsInCart(ShoppingCart cart) {

 return cart.cartSize;

}

// definition of the function GetCostOfCart()

// Determines and returns the total cost of items in cart.

//Has a ShoppingCart parameter.

int GetCostOfCart(ShoppingCart cart) {

 int total = 0;

 int temp = 0;

 for (int i = 0; i < cart.cartSize; ++i) {

   temp = (cart.cartItems[i].itemQuantity * cart.cartItems[i].itemPrice);

   total = total + temp;

 }

 return total;

}

// definition of the function PrintTotal()

// Outputs total of objects in cart. Has a ShoppingCart parameter.

void PrintTotal(ShoppingCart cart) {

 int total = 0;

 int numOfItems = 0;

 for (int i = 0; i < cart.cartSize; ++i) {

   numOfItems = numOfItems + cart.cartItems[i].itemQuantity;

 }

 printf("%s\'s Shopping Cart - %s\n", cart.customerName, cart.currentDate);

 printf("Number of Items: %d\n\n", numOfItems);

 if (cart.cartSize == 0) {

   printf("SHOPPING CART IS EMPTY");
   printf("\nTotal: $0\n");

 } else {

   for (int i = 0; i < cart.cartSize; ++i) {

     printf("%s %d @ $%d = $%d\n", cart.cartItems[i].itemName, cart.cartItems[i].itemQuantity,

       cart.cartItems[i].itemPrice, ((cart.cartItems[i].itemQuantity) * (cart.cartItems[i].itemPrice)));

     total = total + ((cart.cartItems[i].itemQuantity) * (cart.cartItems[i].itemPrice));

   }

   printf("\nTotal: $%d\n", total);

 }

}

// definition of the function PrintDescriptions()

// Outputs each item's description. Has a ShoppingCart parameter.

void PrintDescriptions(ShoppingCart cart) {

 printf("%s's Shopping Cart - %s\n\n", cart.customerName, cart.currentDate);

 printf("Item Descriptions\n");

 for (int i = 0; i < cart.cartSize; ++i) {

   //PrintItemDescription(cart.cartItems[i]);

   printf("%s: %s\n", cart.cartItems[i].itemName, cart.cartItems[i].itemDescription);
 }

}```

ItemPurchase. c


//definition of the function MakeItemBlank()

void MakeItemBlank(struct ItemToPurchase *item) {

  strcpy(( * item).itemName, "none");

  strcpy(( * item).itemDescription, "none");

  ( * item).itemPrice = 0;

  ( * item).itemQuantity = 0;

}

// definition of the function PrintItemCost()

// calculate cost of all item printing cost and name

//and total cost of particular item printing Total cost of all items

void PrintItemCost(struct ItemToPurchase item) {

  printf("%s %d @ $%d = $%d\n", item.itemName, item.itemQuantity, item.itemPrice, (item.itemPrice * item.itemQuantity));

}

// definition of the function PrintItemDescription()

//Has an ItemToPurchase parameter.

void PrintItemDescription(struct ItemToPurchase item) {

  printf("%s: %s.\n", item.itemName, item.itemDescription);

}

И Main. c


#include "ShoppingCart.h"

//definition of the function PrintMenu()

//PrintMenu() has a ShoppingCart parameter,

//and outputs a menu of options to manipulate the shopping cart

void PrintMenu(ShoppingCart userCart) {

  char choice = ' ';

  char c = ' ';

  while (choice != 'q')

  {

    printf("\nMENU\n");

    printf("a - Add item to cart\n");

    printf("r - Remove item from cart\n");

    printf("c - Change item quantity\n");

    printf("i - Output items' descriptions\n");

    printf("o - Output shopping cart\n");

    printf("q - Quit\n\n");

    while (choice != 'a' && choice != 'r' && choice != 'c' &&

      choice != 'i' && choice != 'o' && choice != 'q')

    {

      printf("Choose an option:\n");

      scanf(" %c", &choice);

    }

    //if the user option is a read the item name.

    // item description, item price, and quantity

    // then call the function AddItem() to add the items in the cart

    if (choice == 'a')

    {

      while ((c = getchar()) != EOF && c != '\n');

      char name[50];

      char description[50];

      struct ItemToPurchase item;

      printf("\nADD ITEM TO CART\n");

      printf("Enter the item name:\n");

      fgets(name, 50, stdin);

      int i = 0;

      while (name[i] != '\n') {

        item.itemName[i] = name[i];

        ++i;

      }

      item.itemName[i] = '\0';

      printf("Enter the item description:\n");

      fgets(description, 50, stdin);

      i = 0;

      while (description[i] != '\n') {

        item.itemDescription[i] = description[i];

        ++i;

      }

      item.itemDescription[i] = '\0';

      printf("Enter the item price:\n");

      scanf("%d", &item.itemPrice);

      printf("Enter the item quantity:\n");

      scanf("%d", &item.itemQuantity);

      //call the function AddItem()

      userCart = AddItem(item, userCart);

      printf("\n");

      choice = ' ';

    }

    //if the user option is r read the item name.

    // and remove that item from the item list.

    // then call the function RemoveItem() to remove the items from the cart
    else if (choice == 'r') {

      while ((c = getchar()) != EOF && c != '\n');

      char temp[50];

      char tempStr[50];

      printf("REMOVE ITEM FROM CART\n");

      printf("Enter name of item to remove:\n");

      fgets(temp, 50, stdin);

      int i = 0;

      while (temp[i] != '\n') {

        tempStr[i] = temp[i];

        ++i;

      }

      tempStr[i] = '\0';

      //call the function RemoveItem()

      userCart = RemoveItem(tempStr, userCart);

      choice = ' ';

    }

    //if the user option is c read the item name to be changed.

    // and change the item name from the item list.

    // then call the function ModifyItem() to change the item name from the cart
    else if (choice == 'c') {

      while ((c = getchar()) != EOF && c != '\n');

      char name[50];

      char tempStr[50];

      printf("CHANGE ITEM QUANTITY\n");

      printf("Enter the item name:\n");

      fgets(name, 50, stdin);

      int i = 0;

      while (name[i] != '\n') {

        tempStr[i] = name[i];

        ++i;

      }

      tempStr[i] = '\0';

      userCart = ModifyItem(tempStr, userCart);

      choice = ' ';

    }

    //if the user option is i print the item description.

    // then call the function PrintDescriptions().
    else if (choice == 'i') {

      printf("OUTPUT ITEMS' DESCRIPTIONS\n");

      PrintDescriptions(userCart);

      choice = ' ';

    }

    //if the user option is o print the shopping cart description.

    // then call the function PrintDescriptions().
    else if (choice == 'o') {

      printf("OUTPUT SHOPPING CART\n");

      PrintTotal(userCart);

      choice = ' ';

    }

  }

}

//definition of main() function

int main() {

  //Create an object of type ShoppingCart.

  ShoppingCart userCart;

  userCart.cartSize = 0;

  //prompt the user for a customer's name and today's date.

  //Output the name and date.

  printf("Enter Customer's Name:\n");

  gets(userCart.customerName);

  printf("Enter Today's Date:\n");

  gets(userCart.currentDate);

  printf("\nCustomer Name: %s\n", userCart.customerName);

  printf("Today's Date: %s\n", userCart.currentDate);

  //Call PrintMenu() function.

  PrintMenu(userCart);

  return 0;

}

Это мои ошибки ->

main.c:251:4: warning: statement with no effect [-Wunused-value]
  251 |    ItemToPurchase item;
      |    ^~~~~~~~~~~~~~
main.c:251:18: error: expected ‘;’ before ‘item’
  251 |    ItemToPurchase item;
      |                  ^~~~~
      |                  ;
main.c:252:11: error: ‘item’ undeclared (first use in this function)
  252 |    strcpy(item.itemDescription, "Deer Park, 12 oz.");
      |           ^~~~

Я не понимаю, почему выводится, что мой 'элемент' не объявлен, потому что я объявил его в моей функции printMenu. Все, кроме этого, работает, но я получаю эту ошибку для функций ItemToPurchase, MakeItemBlank (), GetNumItemsInCart () и GetCostOfCart ().

Я только вчера начал изучать указатели. Что касается попыток исправить это go, я искал пропущенные точки с запятой, неправильное использование {} в циклах и проверял свои параметры в своих функциях.

...