我试图写一个代码,可以排序的名字。所以我试着写一个程序,但它并没有按我所希望的那样工作。我要名字按字母顺序排列。我还想根据id的最大值对id进行排序。感谢大家的帮助。对C和一般编码来说有点陌生!

#include <stdio.h>
#include <stdlib.h>

struct class {
  char gender[13];
  char name[13];
  int *id;
};

int compare(const void *s1, const void *s2)
{
  struct class  *e1 = (struct class *)s1;
  struct class *e2 = (struct class *)s2;
  int gendercompare = strcmp(e1->name, e2->name);
  if (gendercompare == 0)
    return e2->gender - e1->gender;
  else
    return -gendercompare;
}

main()
{
  int i;
  int employeecount;

  struct class info[]={{"male","AAA",2000},{"female","BBB",1000},{"male","CCC",3000}};

  employeecount=3;

  for (i = 0; i < employeecount; ++i)
    printf("%i\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);
    printf("\n");

  qsort(info, 3, sizeof(struct class), compare);

  for (i = 0; i < employeecount; ++i)
    printf("%i\t%s\t%s\n", info[i].id, info[i].gender, info[i].name);
}

最佳答案

我认为您可能需要更新compare函数,如下所示:

#include <string.h>

struct class {
  char gender[13];
  char name[13];
  int id;
};

int compare(const void *s1, const void *s2)
{
  struct class *e1 = (struct class *)s1;
  struct class *e2 = (struct class *)s2;
  return strcmp(e1->gender, e2->gender);
}

strcmp足以进行比较。
其他小细节在@Jabberwocky的回答中提到得很好。

关于c - 在C中排序名称和ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54908259/

10-16 20:26
查看更多