usaa24/cv2/program.c

60 lines
1.2 KiB
C
Raw Normal View History

2024-10-04 15:01:12 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2024-10-04 15:11:03 +00:00
#include <ctype.h>
2024-10-04 15:01:12 +00:00
#define MAX_PIZZAS 100
2024-10-04 15:11:03 +00:00
#define MAX_NAME_LENGTH 101
2024-10-04 15:01:12 +00:00
typedef struct {
2024-10-04 15:11:03 +00:00
char name[MAX_NAME_LENGTH];
double price;
2024-10-04 15:01:12 +00:00
} Pizza;
2024-10-04 15:11:03 +00:00
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;
2024-10-04 15:01:12 +00:00
}
2024-10-04 15:11:03 +00:00
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';
2024-10-04 15:01:12 +00:00
}
int main() {
2024-10-04 15:11:03 +00:00
Pizza menu[MAX_PIZZAS];
int count = 0;
while (count < MAX_PIZZAS) {
if (!readPizza(&menu[count])) break;
count++;
2024-10-04 15:01:12 +00:00
}
2024-10-04 15:11:03 +00:00
qsort(menu, count, sizeof(Pizza), compare);
2024-10-04 15:01:12 +00:00
2024-10-04 15:11:03 +00:00
for (int i = 0; i < count; i++) {
printf("%s\n%.6f\n", menu[i].name, menu[i].price);
2024-10-04 15:01:12 +00:00
}
return 0;
}