问题
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);
回答1:
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.
Details are in the references.
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);
}
usage:
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);
}
Results on my data:
Before sorting:
1 John Smith 33 1
2 Jack Smith 18 1
After sorting:
2 Jack Smith 18 1
1 John Smith 33 1
来源:https://stackoverflow.com/questions/48090294/sorting-structures-from-a-file-alphabetically-in-c