sort_str.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* sort_str.c -- reads in strings and sorts them */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define SIZE 81 /* string length limit, including \0 */
  5. #define LIM 20 /* maximum number of lines to be read */
  6. #define HALT "" /* null string to stop input */
  7. void stsrt(char *strings[], int num);/* string-sort function */
  8. char * s_gets(char * st, int n);
  9. int main(void)
  10. {
  11. char input[LIM][SIZE]; /* array to store input */
  12. char *ptstr[LIM]; /* array of pointer variables */
  13. int ct = 0; /* input count */
  14. int k; /* output count */
  15. printf("Input up to %d lines, and I will sort them.\n",LIM);
  16. printf("To stop, press the Enter key at a line's start.\n");
  17. while (ct < LIM && s_gets(input[ct], SIZE) != NULL
  18. && input[ct][0] != '\0')
  19. {
  20. ptstr[ct] = input[ct]; /* set ptrs to strings */
  21. ct++;
  22. }
  23. stsrt(ptstr, ct); /* string sorter */
  24. puts("\nHere's the sorted list:\n");
  25. for (k = 0; k < ct; k++)
  26. puts(ptstr[k]) ; /* sorted pointers */
  27. return 0;
  28. }
  29. /* string-pointer-sorting function */
  30. void stsrt(char *strings[], int num)
  31. {
  32. char *temp;
  33. int top, seek;
  34. for (top = 0; top < num-1; top++)
  35. for (seek = top + 1; seek < num; seek++)
  36. if (strcmp(strings[top],strings[seek]) > 0)
  37. {
  38. temp = strings[top];
  39. strings[top] = strings[seek];
  40. strings[seek] = temp;
  41. }
  42. }
  43. char * s_gets(char * st, int n)
  44. {
  45. char * ret_val;
  46. int i = 0;
  47. ret_val = fgets(st, n, stdin);
  48. if (ret_val)
  49. {
  50. while (st[i] != '\n' && st[i] != '\0')
  51. i++;
  52. if (st[i] == '\n')
  53. st[i] = '\0';
  54. else // must have words[i] == '\0'
  55. while (getchar() != '\n')
  56. continue;
  57. }
  58. return ret_val;
  59. }