在C中按字母顺序对文件中的结构进行排序 [英] Sorting structures from a file alphabetically in C
问题描述
有必要对字段(char last_name [256];)结构上的结构进行排序 并在控制台中显示用户. 怎么做? 预先谢谢你.
It is necessary to make sorting of structures on a field (char last_name [256];) structures Pers and display the user in the console. How to do it? Thank you in advance.
有这样的结构(嵌套):
There is such a structure (with nested):
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;
从文件读取并输出如下所示: 一切都按照从文件中读取的顺序显示
reading from a file and output looks like this: Everything is displayed in the order of reading from the file
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);
推荐答案
要使用stdlib
中的qsort
对结构进行排序,应实现比较两个元素的函数.并比较来自string
的字符串strcmp
.
To use qsort
from stdlib
for sorting of your structures, you should implement function that compares two elements. And to compare strings strcmp
from string
is used.
详细信息位于引用中.
使用first_name
和last_name
进行排序的示例(last_name
是第一个进行比较的情况):
Example for case when both first_name
and last_name
are used for sorting (last_name
is the first for comparison):
#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
这篇关于在C中按字母顺序对文件中的结构进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!