【问题标题】:Sorting structures from a file alphabetically in C在C中按字母顺序对文件中的结构进行排序
【发布时间】:2018-06-13 21:21:47
【问题描述】:

有必要对字段上的结构进行排序 (char last_name [256];) 结构 Pers 并在控制台中显示用户。 怎么做? 提前谢谢你。

有这样的结构(有嵌套):

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);

【问题讨论】:

  • 首先,我希望文件中的记录不超过两条。其次,你不应该只检查fscanf是否返回EOF,如果文件损坏了怎么办?我建议阅读 lines(使用例如 fgets),然后尝试使用 sscanf 解析该行。
  • 你可以看看qsort()。它相当“通用” - 您必须提供自己的功能进行比较。因此,您可以对存储在数组中的所有内容进行排序(并且具有任何顺序)。建议在假设情况下这样做,分配不需要您自己实现排序功能。
  • 至于你的问题,不要循环打印。而是只在循环中读取,然后在sort 数组中读取,最后在您打印的地方进行第二个循环。
  • fscanf (file, "%d%s%s%d%d", %s 应该指定一个宽度,否则你有一个缓冲区溢出漏洞。 %255s

标签: c sorting structure


【解决方案1】:

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

详情在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

【讨论】:

  • 非常感谢!如果文件中的结构大于 2 会怎样。并且它们每行都写在结构的一个元素上
  • 如果要排序的结构数为 N(在您的示例中为 i),您需要:1)for(i = 0; i &lt; N; i++) 和 2)qsort (sw, N, sizeof(struct Pers), compare)。所以你必须在从文件中读取数字 N 时。据我了解,从文件中读取不是本文的主题。
  • 是的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
相关资源
最近更新 更多