C语言实现图书管理系统:按出版日期排序
#include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX_BOOKS 100
typedef struct { char title[101]; char author[101]; char date[11]; } Book;
int compare_dates(const char* date1, const char* date2) { int year1, month1, day1, year2, month2, day2; sscanf(date1, "%d-%d-%d", &year1, &month1, &day1); sscanf(date2, "%d-%d-%d", &year2, &month2, &day2); if (year1 < year2) { return -1; } else if (year1 > year2) { return 1; } else { if (month1 < month2) { return -1; } else if (month1 > month2) { return 1; } else { if (day1 < day2) { return -1; } else if (day1 > day2) { return 1; } else { return 0; } } } }
int compare_books(const void* a, const void* b) { Book* book1 = (Book*)a; Book* book2 = (Book*)b; return compare_dates(book1->date, book2->date); }
int main() { int n, i; Book books[MAX_BOOKS]; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%s %s %s", books[i].title, books[i].author, books[i].date); } qsort(books, n, sizeof(Book), compare_books); for (i = 0; i < n; i++) { printf("%s %s %s\n", books[i].title, books[i].author, books[i].date); } return 0;
原文地址: http://www.cveoy.top/t/topic/ojJf 著作权归作者所有。请勿转载和采集!