//program to read record of 5 books from user
//and write them in a file book.txt
//then read entire records from the file
//display the most expensive book
#include <iostream>
#include <fstream>
using namespace std;
class Book
{
public:
int id;
char name[20];
int nop;
float price;
void readRecord()
{
cout<<"Enter ID: ";
cin>>id;
cout<<"Enter book name: ";
cin>>name;
cout<<"Enter number of pages: ";
cin>>nop;
cout<<"Enter price: ";
cin>>price;
}
void displayRecord()
{
cout<<endl<<"ID: "<<id;
cout<<endl<<"Book Name: "<<name;
cout<<endl<<"No. of Page: "<<nop;
cout<<endl<<"Price: "<<price;
}
float GetMaxPrice()
{
return price;
}
};
int main()
{
Book b[5];
int i;
cout<<"Reading records of book: "<<endl;
for(i=0;i<5;i++)
{
cout<<"Enter record "<<i+1<<":"<<endl;
b[i].readRecord();
}
//writing to a file
fstream file("book.txt",ios::out | ios::binary | ios::in);
cout<<"Writing to a file.....";
for(i=0;i<5;i++)
{
file.write((char*)&b[i],sizeof(b[i]));
}
cout<<"Records have been written to file...";
//reading from file
for(i=0;i<5;i++)
{
file.read((char*)&b[i],sizeof(b[i]));
b[i].displayRecord();
}
//displaying the most expensive book
float maxprice=b[0].price;
for(i=1;i<5;i++)
{
if(maxprice<b[i].price)
maxprice=b[i].price;
}
file.read((char*)&b[i],sizeof(b[i]));
for(i=1;i<5;i++)
{
if(b[i].GetMaxPrice()==maxprice)
{
cout<<endl<<endl<<"The most expensive book is: "<<endl;
b[i].displayRecord();
break;
}
file.read((char*)&b[i],sizeof(b[i]));
}
file.close();
return 0;
}
//and write them in a file book.txt
//then read entire records from the file
//display the most expensive book
#include <iostream>
#include <fstream>
using namespace std;
class Book
{
public:
int id;
char name[20];
int nop;
float price;
void readRecord()
{
cout<<"Enter ID: ";
cin>>id;
cout<<"Enter book name: ";
cin>>name;
cout<<"Enter number of pages: ";
cin>>nop;
cout<<"Enter price: ";
cin>>price;
}
void displayRecord()
{
cout<<endl<<"ID: "<<id;
cout<<endl<<"Book Name: "<<name;
cout<<endl<<"No. of Page: "<<nop;
cout<<endl<<"Price: "<<price;
}
float GetMaxPrice()
{
return price;
}
};
int main()
{
Book b[5];
int i;
cout<<"Reading records of book: "<<endl;
for(i=0;i<5;i++)
{
cout<<"Enter record "<<i+1<<":"<<endl;
b[i].readRecord();
}
//writing to a file
fstream file("book.txt",ios::out | ios::binary | ios::in);
cout<<"Writing to a file.....";
for(i=0;i<5;i++)
{
file.write((char*)&b[i],sizeof(b[i]));
}
cout<<"Records have been written to file...";
//reading from file
for(i=0;i<5;i++)
{
file.read((char*)&b[i],sizeof(b[i]));
b[i].displayRecord();
}
//displaying the most expensive book
float maxprice=b[0].price;
for(i=1;i<5;i++)
{
if(maxprice<b[i].price)
maxprice=b[i].price;
}
file.read((char*)&b[i],sizeof(b[i]));
for(i=1;i<5;i++)
{
if(b[i].GetMaxPrice()==maxprice)
{
cout<<endl<<endl<<"The most expensive book is: "<<endl;
b[i].displayRecord();
break;
}
file.read((char*)&b[i],sizeof(b[i]));
}
file.close();
return 0;
}
No comments:
Post a Comment