#include <iostream>
#include <fstream>
usingnamespace std;
int b;
class book
{
private:
int bookno;
char booktitle[100];
float price;
float total_cost(int);
public:
void input();
void purchase();
void display();
};
void book::input()
{
cout<<"\nEnter book number:";
cin>>bookno;
cout<<"\nEnter book title:";
cin.getline(booktitle, 100);
cout<<"\nEnter price:";
cin>>price;
}
void book::purchase()
{
float p;
cout<<"\nEnter no. of copies:";
cin>>b;
p=total_cost(b);
cout<<"\nTotal cost:"<<p;
}
float book::total_cost(int x)
{
return price*x;
}
void book::display()
{
cout<<"\n\n\nBook number:"<<bookno;
cout<<"\nBook title:"<<booktitle;
cout<<"\nPrice:"<<price;
cout<<"\nTotal cost:"<<total_cost(b);
}
int main()
{
book s[2], t[2];
fstream fs("Book.dat",fstream::in|fstream::out|fstream::binary);
cout<<"\n\nEnter details:";
for (int i=0;i<2;i++)
{
s[i].input();
s[i].purchase();
fs.write((char *)&s[i], sizeof(s[i]));
fs.read((char *)&t[i], sizeof(t[i]));
}
fs.close();
cout<<"\n\n\n\nDetails:";
for (int i=0;i<2;i++)
{
t[i].display();
}
return 0;
}
output:
Enter details:
Enter book number:89
Enter book title:
Enter price:450
Enter no. of copies:2
Total cost:900
Enter book number:74
Enter book title:
Enter price:63
Enter no. of copies:2
Total cost:126
Details:
Book number:2424048
Book title:
Price:6.69737e-039
Total cost:1.33947e-038
Book number:0
Book title:
Price:0
Total cost:0
Input for book titile is not at all allowed as the input doen't even go there.
cout<<"\nEnter book number:";
cin>>bookno;
cout<<"\nEnter book title:";
cin.getline(booktitle, 100);
`getline()' stops at end of line, you press an <Return> after inputting the book number, so you get an empty string as the name.
you may cin.ignore() after using >>