home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list15_7.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  2KB  |  78 lines

  1.  /* Inputs a list of strings from the keyboard, sorts them, */
  2.  /* then displays them on the screen. */
  3.  
  4.  #include <stdio.h>
  5.  #include <string.h>
  6.  
  7.  #define MAXLINES 25
  8.  
  9.  int get_lines(char *lines[]);
  10.  void sort(char *p[], int n);
  11.  void print_strings(char *p[], int n);
  12.  
  13.  char *lines[MAXLINES];
  14.  
  15.  main()
  16.  {
  17.      int number_of_lines;
  18.  
  19.      /* Read in the lines from the keyboard. */
  20.  
  21.      number_of_lines = get_lines(lines);
  22.  
  23.      if ( number_of_lines < 0 )
  24.      {
  25.          puts(" Memory allocation error");
  26.           exit(-1);
  27.      }
  28.  
  29.      sort(lines, number_of_lines);
  30.       print_strings(lines, number_of_lines);
  31.  
  32.  }
  33.  
  34.  int get_lines(char *lines[])
  35. {
  36.       int n = 0;
  37.      char buffer[80];  /* Temporary storage for each line. */
  38.  
  39.      puts("Enter one line at time; enter a blank when done.");
  40.  
  41.      while ((n < MAXLINES) && (gets(buffer) != 0) &&
  42.             (buffer[0] != '\0'))
  43.      {
  44.          if ((lines[n] = (char *)malloc(strlen(buffer)+1)) == NULL)
  45.              return -1;
  46.          strcpy( lines[n++], buffer );
  47.      }
  48.      return n;
  49.  
  50.  } /* End of get_lines() */
  51.  
  52.  void sort(char *p[], int n)
  53.  {
  54.      int a, b;
  55.      char *x;
  56.  
  57.      for (a = 1; a < n; a++)
  58.      {
  59.          for (b = 0; b < n-1; b++)
  60.          {
  61.               if (strcmp(p[b], p[b+1]) > 0)
  62.              {
  63.                   x = p[b];
  64.                   p[b] = p[b+1];
  65.                   p[b+1] = x;
  66.              }
  67.          }
  68.      }
  69.  }
  70.  
  71.  void print_strings(char *p[], int n)
  72.  {
  73.      int count;
  74.  
  75.      for (count = 0; count < n; count++)
  76.          printf("\n%s ", p[count]);
  77.     }
  78.