Error sort_structs_time. Program to use struct and qsort to acccept and store user input; firstname, lastname, country and time. Output should be sorted on time using qsort e.g.
input
BEKELE Tariku ETH 27:31.43
RUPP Galen USA 27:30.90
FARAH Mo GB 27:30.42
output
FARAH Mo GB 27:30.42
RUPP Galen USA 27:30.90
BEKELE Tariku ETH 27:31.43
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct olympics {
//char athlete[25];
char fname[15];
char lname[15];
char country[5];
float time;
};
/* qsort struct comparision function (time float field) */
int struct_cmp_by_time(const void *a, const void *b)
{
struct olympics *ia = (struct olympics *)a;
struct olympics *ib = (struct olympics *)b;
return (int)(60.f*ia->time - 60.f*ib->time);
}
/* struct array printing function */
void print_struct_array(struct olympics *array, size_t len)
{
size_t i;
for(i=0; i<len; i++)
printf("%s %s %s \t %.2f\n", array[i].fname, array[i].lname, array[i].country, array[i].time);
puts("****");
}
/* sorting structs using qsort() */
void sort_structs_time(void)
{
struct olympics structs[] = {
scanf("%s %s %s %.2f\n", fname, lname, country, &time)
};
size_t structs_len = sizeof(structs) / sizeof(struct olympics);
puts("**** Athletes finishing time...");
/* print original struct array */
print_struct_array(structs, structs_len);
/* sort array using qsort functions */
qsort(structs, structs_len, sizeof(struct olympics), struct_cmp_by_time);
/* print sorted struct array */
print_struct_array(structs, structs_len);
}
/* call to the function) */
int main()
{
/* run the function */
sort_structs_time();
return 0;
}
You need to do some changes in your
sort_structs_timeandstruct_cmp_by_timefunctions.It’s obvious that you have not understood C structs and matrices, so do a revision on this topics.
See this qsort documentation and have a look on the comparison function presented there.
There are other ways also to correct your code. I just find this easier to understand .
A better representation of time, imo, is as this:
so you can print the time this way:
(You have to change the parts of your program related to time if you use this representation, i.e. the comparison function.)