NickAndNick

Сортировка массива структур по одному полю

Jul 30th, 2014
311
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <locale.h>
  4. #include <string.h>
  5.  
  6. #define LIMIT 5
  7. #define TITLE_BUFFER 80
  8. #define AUTHOR_BUFFER 64
  9.  
  10. enum points { TITLE, AUTHOR, YEAR };
  11.  
  12. typedef struct Book {
  13.     char title[TITLE_BUFFER];
  14.     char author[AUTHOR_BUFFER];
  15.     int year;
  16. } BOOK;
  17. typedef BOOK* PBOOK;
  18.  
  19. void user(enum points);
  20. BOOK input();
  21. void fill(PBOOK);
  22. void print(BOOK);
  23. void show(PBOOK);
  24. int compare(const void*, const void*);
  25.  
  26. int main() {
  27.     BOOK book[LIMIT];
  28.     fill(book);
  29.     system("cls");
  30.     show(book);
  31.     qsort(book, LIMIT, sizeof(BOOK), compare);
  32.     show(book);
  33.     fflush(stdin);
  34.     getchar();
  35.     return 0;
  36. }
  37.  
  38. int compare(const void* a, const void* b) {
  39.     PBOOK pa = a;
  40.     PBOOK pb = b;
  41.     return strcmp(pa->author, pb->author);
  42. }
  43.  
  44. void fill(PBOOK pbook) {
  45.     int i;
  46.     for (i = 0; i < LIMIT; ++i) pbook[i] = input();
  47. }
  48.  
  49. BOOK input() {
  50.     BOOK book;
  51.     user(TITLE);
  52.     gets_s(book.title, TITLE_BUFFER);
  53.     user(YEAR);
  54.     scanf_s("%i", &book.year);
  55.     fflush(stdin);
  56.     user(AUTHOR);
  57.     gets_s(book.author, AUTHOR_BUFFER);
  58.     return book;
  59. }
  60.  
  61. void show(PBOOK pbook) {
  62.     int i;
  63.     for (i = 0; i < LIMIT; ++i) print(pbook[i]);
  64.     printf("\n");
  65. }
  66.  
  67. void print(BOOK book) {
  68.     printf(" %s, %s, %d", book.author, book.title, book.year);
  69.     printf("\n");
  70. }
  71.  
  72. void user(enum points point) {
  73.     setlocale(LC_CTYPE, ".1251");
  74.     switch (point) {
  75.         case TITLE: printf(" Введите название книги: "); break;
  76.         case AUTHOR: printf(" Введите автора: "); break;
  77.         case YEAR: printf(" Введите год издания: "); break;
  78.     }
  79.     setlocale(LC_CTYPE, ".866");
  80. }
RAW Paste Data