home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / pcmagazi / 1988 / 15 / tryqsort.c < prev    next >
C/C++ Source or Header  |  1988-05-24  |  2KB  |  46 lines

  1. /*
  2.     TRYQSORT.C  Demonstrates use of the library
  3.                 routine 'qsort' to sort strings.
  4.  
  5.     Ray Duncan * PC Magazine May 1988
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <stdlib.h>
  11.  
  12. #define ITEM_LENGTH 80              /* max string length */
  13. #define N_ITEMS     25              /* max number of strings */
  14.                                     /* strings stored here */
  15. static char items[N_ITEMS * ITEM_LENGTH];
  16.  
  17. main(int argc, char *argv[])
  18. {
  19.     int i, j;                       /* some scratch variables */
  20.  
  21.     while(1)                        /* get strings & sort them */
  22.     {
  23.         puts("\nEnter strings to be sorted...");
  24.         i = 0;                      /* initialize string count */
  25.         while(i < N_ITEMS)          /* enforce maximum entries */
  26.         {
  27.             printf("%2d: ", i+1);   /* prompt user */
  28.                                     /* read the keyboard */
  29.             gets(&items[ITEM_LENGTH * i]);
  30.                                     /* last entry if empty line */
  31.             if(items[ITEM_LENGTH * i] == 0) break;
  32.             i++;                    /* bump string counter */
  33.         }
  34.         if(i==0) exit(0);           /* if no strings exit */
  35.                                     /* sort the strings */
  36.         qsort(items, i, ITEM_LENGTH, strcmp);
  37.         puts("\nHere are the sorted strings...");
  38.         j = 0;                      /* initialize string counter */
  39.         while (j < i)               /* display sorted strings */
  40.         {
  41.             printf("%2d: %s\n", j+1, &items[ITEM_LENGTH * j]);
  42.             j++;                    /* bump string counter */
  43.         }
  44.     }
  45. }
  46.