films1.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* films1.c -- using an array of structures */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define TSIZE 45 /* size of array to hold title */
  5. #define FMAX 5 /* maximum number of film titles */
  6. struct film {
  7. char title[TSIZE];
  8. int rating;
  9. };
  10. char * s_gets(char str[], int lim);
  11. int main(void)
  12. {
  13. struct film movies[FMAX];
  14. int i = 0;
  15. int j;
  16. puts("Enter first movie title:");
  17. while (i < FMAX && s_gets(movies[i].title, TSIZE) != NULL &&
  18. movies[i].title[0] != '\0')
  19. {
  20. puts("Enter your rating <0-10>:");
  21. scanf("%d", &movies[i++].rating);
  22. while(getchar() != '\n')
  23. continue;
  24. puts("Enter next movie title (empty line to stop):");
  25. }
  26. if (i == 0)
  27. printf("No data entered. ");
  28. else
  29. printf ("Here is the movie list:\n");
  30. for (j = 0; j < i; j++)
  31. printf("Movie: %s Rating: %d\n", movies[j].title,
  32. movies[j].rating);
  33. printf("Bye!\n");
  34. return 0;
  35. }
  36. char * s_gets(char * st, int n)
  37. {
  38. char * ret_val;
  39. char * find;
  40. ret_val = fgets(st, n, stdin);
  41. if (ret_val)
  42. {
  43. find = strchr(st, '\n'); // look for newline
  44. if (find) // if the address is not NULL,
  45. *find = '\0'; // place a null character there
  46. else
  47. while (getchar() != '\n')
  48. continue; // dispose of rest of line
  49. }
  50. return ret_val;
  51. }