From af361fdfeb143d7eca26e99e616741632c68fa3b Mon Sep 17 00:00:00 2001 From: Weber Date: Fri, 4 Oct 2024 15:11:03 +0000 Subject: [PATCH] test --- cv2/program.c | 73 +++++++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/cv2/program.c b/cv2/program.c index a2db5c5..4cf68da 100644 --- a/cv2/program.c +++ b/cv2/program.c @@ -1,56 +1,59 @@ #include #include #include +#include #define MAX_PIZZAS 100 -#define MAX_TITLE_LENGTH 100 -#define MAX_PRICE_LENGTH 10 +#define MAX_NAME_LENGTH 101 typedef struct { - char title[MAX_TITLE_LENGTH]; - float price; + char name[MAX_NAME_LENGTH]; + double price; } Pizza; -int compare_pizzas(const void *a, const void *b) { - Pizza *pizza1 = (Pizza *)a; - Pizza *pizza2 = (Pizza *)b; - if (pizza1->price < pizza2->price) { - return -1; - } else if (pizza1->price > pizza2->price) { - return 1; - } else { - return strcmp(pizza1->title, pizza2->title); +int compare(const void *a, const void *b) { + const Pizza *pizzaA = (const Pizza *)a; + const Pizza *pizzaB = (const Pizza *)b; + + + if (pizzaA->price != pizzaB->price) { + return (pizzaA->price < pizzaB->price) ? -1 : 1; } + + + return strcasecmp(pizzaA->name, pizzaB->name); +} + + +int readPizza(Pizza *pizza) { + if (!fgets(pizza->name, sizeof(pizza->name), stdin)) return 0; + pizza->name[strcspn(pizza->name, "\n")] = 0; + + char priceStr[10]; + if (!fgets(priceStr, sizeof(priceStr), stdin)) return 0; + priceStr[strcspn(priceStr, "\n")] = 0; + + char *endptr; + pizza->price = strtod(priceStr, &endptr); + return *endptr == '\0'; } int main() { - Pizza pizzas[MAX_PIZZAS]; - int num_pizzas = 0; + Pizza menu[MAX_PIZZAS]; + int count = 0; - while (num_pizzas < MAX_PIZZAS) { - printf("Enter pizza title: "); - fgets(pizzas[num_pizzas].title, MAX_TITLE_LENGTH, stdin); - pizzas[num_pizzas].title[strcspn(pizzas[num_pizzas].title, "\n")] = 0; - - printf("Enter pizza price: "); - char price_str[MAX_PRICE_LENGTH]; - fgets(price_str, MAX_PRICE_LENGTH, stdin); - price_str[strcspn(price_str, "\n")] = 0; - - char *endptr; - pizzas[num_pizzas].price = strtof(price_str, &endptr); - if (endptr == price_str || *endptr != '\0') { - break; - } - - num_pizzas++; + while (count < MAX_PIZZAS) { + if (!readPizza(&menu[count])) break; + count++; } - qsort(pizzas, num_pizzas, sizeof(Pizza), compare_pizzas); + + qsort(menu, count, sizeof(Pizza), compare); - for (int i = 0; i < num_pizzas; i++) { - printf("%s\n%.6f\n", pizzas[i].title, pizzas[i].price); + + for (int i = 0; i < count; i++) { + printf("%s\n%.6f\n", menu[i].name, menu[i].price); } return 0;