I am a student in C++.We undertook a school project to develop a library information system.We are only allowed to use Turbo C++ version 3 compiler.We cannot use ANSI/ISO C++(Not in our syllabus.)The following is my problem:
In my project, I have a class books.When the program is first run, it would create n number of object of books class.The data members would then be given values.It is then saved in a binary file.When the software is run again,the program asks whether the books are to be initialized?(i.e, clear the binary file and make another set of objects and write them to the disk.)If no is selected,the program will display the information of the books.i.e, it will retreive the information from memmory.In my program,Even though I create many objects,only the values of one object is outputed.
A simplified version of the code is given below:
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
class books
{
int bcopies;
public:
void init()
{
cout<<"Enter the no.of copies:";
cin>>bcopies;
}
void putvalue()
{
cout<<"Copies:"<<bcopies<<"\n";
}
};
int choice,n,i;
int main()
{
clrscr();
fstream file;
cout<<"Initialize?(1/2)";
cin>>choice;
if(choice==1)
{
cout<<"Enter the no. of books:";
cin>>n;
--n;
file.open("library.dat",ios::out|ios::binary|ios::trunc);
fstream f;
f.open("n.dat",ios::out|ios::binary);
f.write((char*)&n,sizeof(int));
books * B=new books[n];
for(i=0;i<=n;i++)
{
clrscr();
B[i].init();
file.write((char*)&B[i],sizeof(books));
}
file.close();
f.close();
}
fstream f;
file.open("library.dat",ios::in|ios::binary);
f.open("n.dat",ios::in|ios::binary);
books * B=new books[n];
file.seekg(0,ios::beg);
file.read((char*)&B[i],sizeof(books));
for(i=0;i<=n;i++)
{
B[i].putvalue();
}
getch();
return 0;
}
OUTPUT:
__________________________
Initialize?(1/2) 1
Enter the number of books: 3
__________________________
Enter the number of copies:2
__________________________
Enter the number of copies:1
__________________________
Enter the number of copies:3
Copies:2
Copies:1
Copies:3
__________________________
<Program is closed,and excecuted again:>
__________________________
Initialize(1/2) 2
Copies:2
__________________________
why the data from the other objects are not displayed?