The Program in C program that creates a structure for a book, reads information about a book from the user, and then displays that information is given below:
#include <stdio.h>
#include <string.h>
struct book {
char title[50];
char author[50];
int pages;
float price;
};
int main() {
struct book new_book;
printf("Enter the title of the book: ");
fgets(new_book.title, 50, stdin);
new_book.title[strcspn(new_book.title, "\n")] = 0;
printf("Enter the author of the book: ");
fgets(new_book.author, 50, stdin);
new_book.author[strcspn(new_book.author, "\n")] = 0;
printf("Enter the number of pages in the book: ");
scanf("%d", &new_book.pages);
printf("Enter the price of the book: ");
scanf("%f", &new_book.price);
printf("Title: %s\n", new_book.title);
printf("Author: %s\n", new_book.author);
printf("Pages: %d\n", new_book.pages);
printf("Price: $%.2f\n", new_book.price);
return 0;
}
Output:
Enter the title of the book: Master an art of coding with Codeauri
Enter the author of the book: Codeauri
Enter the number of pages in the book: 299
Enter the price of the book: 99
Title: Master an art of coding with Codeauri
Author: Codeauri
Pages: 299
Price: $99.00
Pro-Tips💡
The line struct book {
defines a structure named “book” with four members: title
, author
, pages
, and price
. These members are of type char
, char
, int
, and float
respectively.
In the main function, an instance of the book structure is created, named new_book
.
The next lines are used to prompt the user to enter the title, author, number of pages and price of the book.
The title and the author are read using fgets
, which reads a line of text from the standard input (keyboard) and stores it in the title
and author
members of the new_book
structure.
The newline characters are removed using strcspn
function from the input.
Then, the number of pages and the price of the book are read using scanf
function.
Finally, the information is displayed using printf
function, where the structure members are accessed by using the dot operator (.
) to reference the specific member of the structure.
At the end, the program returns 0 to indicate that it has run successfully.
Please note that fgets
reads the newline character as well, so it is removed using strcspn
function to get rid of it,
also the program will not check if the input is a valid number for pages and price of book, so it is a good practice to check the user input to avoid unexpected results.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.