In this C++ program, we will store the information of a book in a structure variable and then display it in screen. We want to store following information for a book
Name, Price and ISBN. Here is a sample book record :
Name : Harry Potter
Price : 500
ISBN Code : 7645364
To store the information of a book, we will define an Book structure having three member variable name, price and ISBN.
struct Book { char name[100]; int price; int ISBN; };
Then we will create a variable of structure Book, let's say book1. Then to access the members of book1, we will use member access operator or dot(.) operator.
- We can declare any number of member variables inside a structure.
- Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
- Keyword struct is used to declare a structure.
- We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.
C++ Program to Store Information of a Book in a Structure
#include <iostream> using namespace std; // A structure for book struct Book { char name[100]; int price; int ISBN; }; int main() { Book b; cout << "Enter name of book\n"; cin.getline(b.name, 100); cout << "Enter price of employee\n"; cin >> b.price; cout << "Enter ISBN code\n"; cin >> b.ISBN; // Printing Book details cout << "\n*** Book Details ***" << endl; cout << "Name : " << b.name << endl; cout << "Price : " << b.price << endl; cout << "ISBN Code : " << b.ISBN; return 0; }Output
Enter name of book Harry Potter Enter price of employee 500 Enter ISBN code 6453645 *** Book Details *** Name : Harry Potter Price : 500 ISBN Code : 7645364
In above program, we first declare a variable of type Book as
Book b;
Then we ask user to enter book details i.e Name, Price and ISBN and store it in corresponding fields of structure variable b. Finally we print the information of variable b on screen using cout.
Recommended Posts