在C中按字母顺序从文件中排序结构

问题描述 投票:1回答:1

有必要对字段(char last_name [256];)结构进行排序,并在控制台中显示用户。怎么做?先感谢您。

有这样的结构(嵌套):

struct Pers {
    int id;
    char first_name[256];
    char last_name[256];
    struct {
        int age;
        int status;
    } st;
} Pers;


struct Pers sw[2];
char i=0;

从文件和输出中读取如下所示:所有内容都按照从文件中读取的顺序显示

 FILE *file;
 file = fopen("1.txt", "r");
 while ( fscanf(file, "%d%s%s%d%d", &sw[i].id,sw[i].first_name,sw[i].last_name,&sw[i].st.age,&sw[i].st.status) != EOF) 
 {

     printf("%d %s %s %d %d\n", sw[i].id, sw[i].first_name, sw[i].last_name, sw[i].st.age, sw[i].st.status);
        i++;
 }

 fclose(file);
c sorting structure
1个回答
1
投票

要使用qsort中的stdlib对结构进行排序,您应该实现比较两个元素的函数。并使用来自strcmp的字符串string进行比较。

详细信息在references

使用first_namelast_name进行排序的情况示例(last_name是第一个用于比较):

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

int compare (const void * a, const void * b)
{
  const struct Pers * first = (const struct Pers *) a;
  const struct Pers * second = (const struct Pers *) b;
  // compare last names and check result. can be also:
  // if( !strcmp(first->last_name, second->last_name) )
  if( 0 == strcmp(first->last_name, second->last_name) )
      // compare first names if last names are equal
      return strcmp(first->first_name, second->first_name);
  else
      return strcmp(first->last_name, second->last_name);
}

用法:

    printf("Before sorting:\n");
    for(i = 0; i < 2; i++)
    {
        printf("%d %s %s %d %d\n",sw[i].id,sw[i].first_name,sw[i].last_name,sw[i].st.age,sw[i].st.status);
    }
    qsort (sw, 2, sizeof(struct Pers), compare);
    printf("After sorting:\n");
    for(i = 0; i < 2; i++)
    {
        printf("%d %s %s %d %d\n",sw[i].id,sw[i].first_name,sw[i].last_name,sw[i].st.age,sw[i].st.status);
    }

我的数据结果:

Before sorting:
1 John Smith 33 1
2 Jack Smith 18 1
After sorting:
2 Jack Smith 18 1
1 John Smith 33 1
© www.soinside.com 2019 - 2024. All rights reserved.