usaa20/cv2/program.c

59 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_LEN 100
#define LIST_SIZE 128
typedef struct {
char name[LINE_LEN];
float price;
} pizza;
int get_line(char *name);
int get_pizza(pizza *p_item);
int compare_pizza(const void* pVoid1, const void* pVoid2);
int main() {
pizza items[LIST_SIZE];
memset(items,0,sizeof(items));
int count = 0;
while(get_pizza(items + count)) {
count++;
}
qsort(items, count, sizeof(pizza), compare_pizza);
int i = 0;
while(i < count) {
printf("%s\n%f\n", items[i].name, items[i].price);
i++;
}
return 0;
}
int get_line(char *name)
{
memset(name, 0, LINE_LEN);
char* r = fgets(name, LINE_LEN, stdin);
if (r == NULL || name[1] == 0) {
return 0;
}
int n = strlen(name);
if (name[n - 1] == '\n')
name[n - 1] = 0;
return 1;
}
int get_pizza(pizza *p_item)
{
int res = get_line(p_item->name);
char price_string[LINE_LEN];
res += get_line(price_string);
if (res != 2) return 0;
sscanf(price_string, "%f", &(p_item->price));
if(p_item->price == 0.) return 0;
return 1;
}
int compare_pizza(const void* pVoid1, const void* pVoid2) {
pizza* pPizza1 = (pizza*) pVoid1;
float price1 = pPizza1->price;
pizza* pPizza2 = (pizza*) pVoid2;
float price2 = pPizza2->price;
float r = price1 - price2;
if (r > 0.) return 1;
if (r < 0.) return -1;
if (r == 0.) return 0;
}