films3.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* films3.c -- using an ADT-style linked list */
  2. /* compile with list.c */
  3. #include <stdio.h>
  4. #include <stdlib.h> /* prototype for exit() */
  5. #include "list.h" /* defines List, Item */
  6. void showmovies(Item item);
  7. char * s_gets(char * st, int n);
  8. int main(void)
  9. {
  10. List movies;
  11. Item temp;
  12. /* initialize */
  13. InitializeList(&movies);
  14. if (ListIsFull(&movies))
  15. {
  16. fprintf(stderr,"No memory available! Bye!\n");
  17. exit(1);
  18. }
  19. /* gather and store */
  20. puts("Enter first movie title:");
  21. while (s_gets(temp.title, TSIZE) != NULL && temp.title[0] != '\0')
  22. {
  23. puts("Enter your rating <0-10>:");
  24. scanf("%d", &temp.rating);
  25. while(getchar() != '\n')
  26. continue;
  27. if (AddItem(temp, &movies)==false)
  28. {
  29. fprintf(stderr,"Problem allocating memory\n");
  30. break;
  31. }
  32. if (ListIsFull(&movies))
  33. {
  34. puts("The list is now full.");
  35. break;
  36. }
  37. puts("Enter next movie title (empty line to stop):");
  38. }
  39. /* display */
  40. if (ListIsEmpty(&movies))
  41. printf("No data entered. ");
  42. else
  43. {
  44. printf ("Here is the movie list:\n");
  45. Traverse(&movies, showmovies);
  46. }
  47. printf("You entered %d movies.\n", ListItemCount(&movies));
  48. /* clean up */
  49. EmptyTheList(&movies);
  50. printf("Bye!\n");
  51. return 0;
  52. }
  53. void showmovies(Item item)
  54. {
  55. printf("Movie: %s Rating: %d\n", item.title,
  56. item.rating);
  57. }
  58. char * s_gets(char * st, int n)
  59. {
  60. char * ret_val;
  61. char * find;
  62. ret_val = fgets(st, n, stdin);
  63. if (ret_val)
  64. {
  65. find = strchr(st, '\n'); // look for newline
  66. if (find) // if the address is not NULL,
  67. *find = '\0'; // place a null character there
  68. else
  69. while (getchar() != '\n')
  70. continue; // dispose of rest of line
  71. }
  72. return ret_val;
  73. }