简体   繁体   中英

How to eliminate duplicates in a struct, and use qsort to sort them in C

I am trying to find people in my struct from a specific country, eliminate duplicates and sort the remainders after team and name with qsort.

My struct is as following:

struct rider_info{
  char race_name[30];
  char name[50];
  char lastname[30];
  int age;
  char team[4];
  char country[4];
  };

So some of the people in the file i am reading into my struct appears in multiple races. I therefore need to eliminate duplicates but i am not sure how that is done. And thereafter i need to sort those people with qsort after team and name. I have made a try but it just printed all the people from that specific country i needed. Here is the code as it is at this point:

void print_belgian_riders(FILE *fp, int j, rider_info person[j]) {
  char str[4] = "BEL"; //i need to print Belgian riders
  char line[128];
  int lines = count_lines();    
  for (j = 0; j < lines; ++j) {
      if (strcmp(person[j].country, str) == 0) {
          qsort(person, 20, sizeof(person), struct_comp_team);
          printf("%s %s %d %s %s ",
               person[j].name,
               person[j].lastname,
               person[j].age,
               person[j].team,
               person[j].country);
               printf("\n");

      }

   }
}

And here is my compare function for sorting after team and name:

int struct_comp_team(const void *ep1, const void *ep2) {
  int TeamSort = strcmp((((rider_info*)ep1)->team), ((rider_info*)ep2)->team);
  int lastNameSort = strcmp(((rider_info*)ep1)->lastname, ((rider_info*)ep2)->lastname);

  if (TeamSort != 0) {
      return (TeamSort);

  } 
  else if (lastNameSort != 0) {
      return lastNameSort;
  }
}

My compare function is not working, and i am not sure what is wrong with it, does anybody have an idea about how to do it? Is there also someone who had an idea about how i should eliminate duplicates?

Modify your compare function as per mch advice.

int struct_comp_team(const void *ep1, const void *ep2) {
  int TeamSort = strcmp((((rider_info*)ep1)->team), ((rider_info*)ep2)->team);
  int lastNameSort = strcmp(((rider_info*)ep1)->lastname, ((rider_info*)ep2)->lastname);

  if (TeamSort != 0) {
      return (TeamSort);

  } 
  else if (lastNameSort != 0) {
      return lastNameSort;
  }
  return 0;//duplicate value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM