C程序以结构体存储学生记录,并按姓名进行排序

2023年 8月 27日 67.5k 0

C程序以结构体存储学生记录,并按姓名进行排序

{{ student_id = 1, student_name = nupur, student_percentage = 98},
{ student_id = 2, student_name = Akash, student_percentage = 75},
{ student_id = 3, student_name = Yash, student_percentage = 62},
{ student_id = 4, student_name = Jyoti, student_percentage = 87},
{ student_id = 5, student_name = Ramlal, student_percentage = 80}}

输出 − 学生记录 =

{{ student_id = 2, student_name = Akash, student_percentage = 75},
{ student_id = 4, student_name = Jyoti, student_percentage = 87},
{ student_id = 1, student_name = nupur, student_percentage = 98},
{ student_id = 5, student_name = Ramlal, student_percentage = 80},
{ student_id = 3, student_name = Yash, student_percentage = 62}}

登录后复制

为了解决这个问题,我们首先会创建一个存储学生详细信息的结构。现在,我们将使用qsort()函数,并在该函数中定义一个比较器函数,该函数将使用strcmp()方法比较结构的名称。

示例

将学生记录存储为结构并按名称排序的程序

在线演示

//C program to store Student records as Structures and Sort them by Name
#include
#include
#include
struct Student {
int student_id;
char* student_name;
int student_percentage;
};
int comparator(const void* s1, const void* s2){
return strcmp(((struct Student*)s1)->student_name,((struct Student*)s2)->student_name);
}
int main() {
int n = 5;
struct Student arr[n];
//student 1
arr[0].student_id = 1;
arr[0].student_name = "Nupur";
arr[0].student_percentage = 98;
//student 2
arr[1].student_id = 2;
arr[1].student_name = "Akash";
arr[1].student_percentage = 75;
//student 3
arr[2].student_id = 3;
arr[2].student_name = "Yash";
arr[2].student_percentage = 62;
//student 4
arr[3].student_id = 4;
arr[3].student_name = "Jyoti";
arr[3].student_percentage = 87;
//student 5
arr[4].student_id = 5;
arr[4].student_name = "Ramlal";
arr[4].student_percentage = 80;
printf("Unsorted Student Record:

");
for (int i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d

", arr[i].student_id, arr[i].student_name, arr[i].student_percentage);
}
qsort(arr, n, sizeof(struct Student), comparator);
printf("

Student Records sorted by Name:

");
for (int i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d

", arr[i].student_id, arr[i].student_name, arr[i].student_percentage);
}
return 0;
}

登录后复制

输出

Unsorted Student Record:
Id = 1, Name = Nupur, Age = 98
Id = 2, Name = Akash, Age = 75
Id = 3, Name = Yash, Age = 62
Id = 4, Name = Jyoti, Age = 87
Id = 5, Name = Ramlal, Age = 80
Student Records sorted by Name:
Id = 2, Name = Akash, Age = 75
Id = 4, Name = Jyoti, Age = 87
Id = 1, Name = Nupur, Age = 98
Id = 5, Name = Ramlal, Age = 80
Id = 3, Name = Yash, Age = 62

登录后复制

以上就是C程序以结构体存储学生记录,并按姓名进行排序的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论