Wednesday, 2 August 2017

CBSE Class 12 - C++ Practical Class Design and Binary File Handling - Snippet-7 (#cbseNotes)

C++ Practical
Class Design and Binary File Handling Snippet-7

CBSE Class 12 - Computer Science - C++ Practical Class Design Snippet-6 (#cbseNotes)

Question :  Write a program in c++ to create a binary file and write objects of class BOOK to it and display them on screen after reading from the file.

Answer:





// Question: 
// Write a program in c++ to create a binary file and write
// objects of class BOOK to it
// and display them on screen after reading from the file.
//

#include <iostream.h>
#include <fstream.h>
#include <conio.h>

int p;
class book { 
 int book_no;
 char book_title[80];
 float price;
    float total_cost(int n)
      {
     float p;
     p=n*price;
     return p;
     }

    public :
 void input()
     {
  cout<<"\nEnter Book no. : ";
  cin>>book_no;
  cout<<"Enter book title : ";
  cin.get();
  cin.getline(book_title,80);
  cout<<"Enter book price : ";
  cin>>price;
  }

     void purchase()
     {
  cout<<"Enter number of copies to be purchased : "; cin>>p;
  cout<<"Total cost (in Rs ) = "<<total_cost(p)<<"\n";
     }

     void display()
     {
  cout<<"\nBook title is : "<<book_title;
  cout<<"\nBook number is : "<<book_no;
  cout<<"\nPrice of book is : "<<price;
  cout<<"\nTotal cost of "<<p<<" books => "<<total_cost(p)<<" Rs\n";
     }

};

void main()
{
 clrscr();
 book p[3];

 fstream bo;
 cout<<"------------------------Enter Three Books Details---------------------------\n";

 bo.open("xy.txt",ios::out|ios::binary);

 int i;
 for(i=0; i<3; i++)
 {
  book bkobj;
  bkobj.input();
  bkobj.purchase();
  // Writing to  the binary file
  bo.write((char *)&bkobj,sizeof(bkobj));
 }
 bo.close();
 // open file in read mode
 bo.open("xy.txt",ios::in |ios::binary);
 for(i=0; i<3; i++)
  {
  //Reading from the binary file.
  bo.read((char *)&p[i], sizeof(p[i]));
  }
 bo.close();
 cout<<"\n----------------------- Book Details ------------------------------------";
 for(i=0; i<3; i++)
 {
  p[i].display();
 }
 getch();
}

No comments:

Post a Comment

We love to hear your thoughts about this post!

Note: only a member of this blog may post a comment.