1
0

films2.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* films2.c -- using a linked list of structures */
  2. #include <stdio.h>
  3. #include <stdlib.h> /* has the malloc prototype */
  4. #include <string.h> /* has the strcpy prototype */
  5. #define TSIZE 45 /* size of array to hold title */
  6. struct film {
  7. char title[TSIZE];
  8. int rating;
  9. struct film * next; /* points to next struct in list */
  10. };
  11. char * s_gets(char * st, int n);
  12. int main(void)
  13. {
  14. struct film * head = NULL;
  15. struct film * prev, * current;
  16. char input[TSIZE];
  17. /* Gather and store information */
  18. puts("Enter first movie title:");
  19. while (s_gets(input, TSIZE) != NULL && input[0] != '\0')
  20. {
  21. current = (struct film *) malloc(sizeof(struct film));
  22. if (head == NULL) /* first structure */
  23. head = current;
  24. else /* subsequent structures */
  25. prev->next = current;
  26. current->next = NULL;
  27. strcpy(current->title, input);
  28. puts("Enter your rating <0-10>:");
  29. scanf("%d", &current->rating);
  30. while(getchar() != '\n')
  31. continue;
  32. puts("Enter next movie title (empty line to stop):");
  33. prev = current;
  34. }
  35. /* Show list of movies */
  36. if (head == NULL)
  37. printf("No data entered. ");
  38. else
  39. printf ("Here is the movie list:\n");
  40. current = head;
  41. while (current != NULL)
  42. {
  43. printf("Movie: %s Rating: %d\n",
  44. current->title, current->rating);
  45. current = current->next;
  46. }
  47. /* Program done, so free allocated memory */
  48. current = head;
  49. while (current != NULL)
  50. {
  51. free(current);
  52. current = current->next;
  53. }
  54. printf("Bye!\n");
  55. return 0;
  56. }
  57. char * s_gets(char * st, int n)
  58. {
  59. char * ret_val;
  60. char * find;
  61. ret_val = fgets(st, n, stdin);
  62. if (ret_val)
  63. {
  64. find = strchr(st, '\n'); // look for newline
  65. if (find) // if the address is not NULL,
  66. *find = '\0'; // place a null character there
  67. else
  68. while (getchar() != '\n')
  69. continue; // dispose of rest of line
  70. }
  71. return ret_val;
  72. }