manybook.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* manybook.c -- multiple book inventory */
  2. #include <stdio.h>
  3. #include <string.h>
  4. char * s_gets(char * st, int n);
  5. #define MAXTITL 40
  6. #define MAXAUTL 40
  7. #define MAXBKS 100 /* maximum number of books */
  8. struct book { /* set up book template */
  9. char title[MAXTITL];
  10. char author[MAXAUTL];
  11. float value;
  12. };
  13. int main(void)
  14. {
  15. struct book library[MAXBKS]; /* array of book structures */
  16. int count = 0;
  17. int index;
  18. printf("Please enter the book title.\n");
  19. printf("Press [enter] at the start of a line to stop.\n");
  20. while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
  21. && library[count].title[0] != '\0')
  22. {
  23. printf("Now enter the author.\n");
  24. s_gets(library[count].author, MAXAUTL);
  25. printf("Now enter the value.\n");
  26. scanf("%f", &library[count++].value);
  27. while (getchar() != '\n')
  28. continue; /* clear input line */
  29. if (count < MAXBKS)
  30. printf("Enter the next title.\n");
  31. }
  32. if (count > 0)
  33. {
  34. printf("Here is the list of your books:\n");
  35. for (index = 0; index < count; index++)
  36. printf("%s by %s: $%.2f\n", library[index].title,
  37. library[index].author, library[index].value);
  38. }
  39. else
  40. printf("No books? Too bad.\n");
  41. return 0;
  42. }
  43. char * s_gets(char * st, int n)
  44. {
  45. char * ret_val;
  46. char * find;
  47. ret_val = fgets(st, n, stdin);
  48. if (ret_val)
  49. {
  50. find = strchr(st, '\n'); // look for newline
  51. if (find) // if the address is not NULL,
  52. *find = '\0'; // place a null character there
  53. else
  54. while (getchar() != '\n')
  55. continue; // dispose of rest of line
  56. }
  57. return ret_val;
  58. }