This commit is contained in:
Valér Jakubčo 2021-10-14 16:42:58 +02:00
parent 788b9ca2fa
commit b0efda8298

View File

@ -8,20 +8,61 @@
#define NAMESIZE 50 #define NAMESIZE 50
struct menu { struct menu {
char name[SIZE]; char name[SIZE];
float price; float price;
}; };
int compare_name(const void* c1, const void* c2){ // function to compare names alphabetically
struct menu* p1 = (struct menu* ) c1; int compare_name(const void* c1, const void* c2);
struct menu* p2 = (struct menu* ) c2;
return strcmp(p1->name,p2->name); // function to compare floats
int compare_float(const void* c1, const void* c2);
int main(){
struct menu food_database[SIZE];
memset(food_database, 0, SIZE*sizeof(struct menu));
int meal_counter = 0;
char temp[20];
char* ptr1 = NULL;
char* ptr2 = NULL;
while(1){
// load name into struct
ptr1 = fgets(food_database[meal_counter].name, NAMESIZE, stdin);
if ( ptr1 == NULL ){
break;
}
// load price into struct
ptr2 = fgets(temp, 20, stdin);
food_database[meal_counter].price = strtof(temp, NULL);
if ( ptr2 == NULL || food_database[meal_counter].price == 0){
break;
}
meal_counter++;
}
// first sort by name, then by price
qsort(food_database,meal_counter,sizeof(struct menu),compare_name);
qsort(food_database,meal_counter,sizeof(struct menu),compare_float);
// print results
for(int i=0; i<meal_counter; i++){
printf("%s",food_database[i].name);
printf("%f\n",food_database[i].price);
} }
return 0;
}
int compare_float(const void* c1, const void* c2){ int compare_float(const void* c1, const void* c2){
struct menu* p1 = (struct menu* ) c1; struct menu* p1 = (struct menu* ) c1;
struct menu* p2 = (struct menu* ) c2; struct menu* p2 = (struct menu* ) c2;
@ -35,40 +76,11 @@ int compare_float(const void* c1, const void* c2){
} }
int main(){ int compare_name(const void* c1, const void* c2){
struct menu* p1 = (struct menu* ) c1;
struct menu* p2 = (struct menu* ) c2;
return strcmp(p1->name,p2->name);
struct menu food_database[SIZE];
memset(food_database, 0, SIZE*sizeof(struct menu));
// load name into struct
int meal_counter = 0;
char temp[20];
char* ptr1 = NULL;
char* ptr2 = NULL;
while(1){
ptr1 = fgets(food_database[meal_counter].name, NAMESIZE, stdin);
if ( ptr1 == NULL ){
break;
}
ptr2 = fgets(temp, 20, stdin);
food_database[meal_counter].price = strtof(temp, NULL);
if ( ptr2 == NULL || food_database[meal_counter].price == 0){
break;
}
meal_counter++;
}
qsort(food_database,meal_counter,sizeof(struct menu),compare_name);
qsort(food_database,meal_counter,sizeof(struct menu),compare_float);
for(int i=0; i<meal_counter; i++){
printf("%s",food_database[i].name);
printf("%f\n",food_database[i].price);
} }
return 0;
}