pc013.c (1968B)
1 /* Write a C program that defines a structure named Book with attributes bookID (int), 2 title (string), and price (float). Include a user-defined function named updatePrice 3 with the signature: void updatePrice(struct Book *b, float newPrice); 4 The program should: 5 * Accept details for one book from the user. 6 * Display the details before the update. 7 * Use the function to update the price of the book. 8 * Display the updated details.*/ 9 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 14 typedef struct Book 15 { 16 int bookID; 17 float price; 18 char title[20]; 19 } Book; 20 21 void acceptDetails(Book *); 22 void displayDetails(Book *); 23 void updatePrice(struct Book *, float); 24 25 int main() 26 { 27 Book book1; 28 float newPrice; 29 acceptDetails(&book1); 30 displayDetails(&book1); 31 printf("\n\nEnter the updated price: "); 32 if (scanf("%f", &newPrice) != 1) 33 { 34 printf("\nInvalid Price!"); 35 exit(1); 36 } 37 updatePrice(&book1, newPrice); 38 displayDetails(&book1); 39 return 0; 40 } 41 42 void acceptDetails(Book *book) 43 { 44 char *p; 45 printf("\n== Enter details for the book ==\n"); 46 printf("Enter Book ID: "); 47 if (scanf("%d", &book->bookID) != 1) 48 { 49 printf("\nInvalid Book ID!"); 50 exit(1); 51 } 52 while (getchar() != '\n') 53 ; 54 printf("Enter Book Title: "); 55 if (fgets(book->title, sizeof(book->title), stdin) == NULL) 56 { 57 printf("\nError reading input!"); 58 exit(1); 59 } 60 p = strchr(book->title, '\n'); 61 if (p) 62 *p = '\0'; 63 printf("Enter Price: "); 64 if (scanf("%f", &book->price) != 1) 65 { 66 printf("\nInvalid Price!"); 67 exit(1); 68 } 69 } 70 71 void displayDetails(Book *book) 72 { 73 printf("\n== Details of the Book =="); 74 printf("\nBook ID: %d", book->bookID); 75 printf("\nBook Title: %s", book->title); 76 printf("\nBook Price: %g", book->price); 77 } 78 79 void updatePrice(struct Book *book, float newPrice) 80 { 81 book->price = newPrice; 82 }