[img]
http://lengejoorab.persiangig.ir/c++problem.JPG[/img]
This is simple program. theres a class whit a string and an integer. it gets data as objects of this class and save s it in a file (left pic). I can view them correctly after this (middle pic). But if i close the program and then run it again i 'll see view the file incorrectly (right pic).
#include <iostream>
#include <conio>
#include <fstream>
#include <stdio>
class data
{
int n;
char *st;
public:
data();
void getdata();
void showdata();
};
//***********************
data::data()
{
st=new char[40];
}
void data::getdata()
{
cout<<"Enter n: ";
cin>>n;
cout<<"Enter string: ";
gets(st);
}
void data::showdata()
{
cout<<"n: "<<n<<endl;
puts(st);
}
//***********************
void enter();
void view();
//***********************
void main()
{
char ans;
while(1)
{
clrscr();
cout<<"1)New data\n2)View\n3)Exit";
ans=getch();
switch(ans)
{
case '1': enter(); break;
case '2': view(); break;
case '3':return;
}
}
}
//***********************
void enter()
{
clrscr();
data d;
ofstream ofile;
ofile.open("Data",ios::binary|ios::app);
d.getdata();
ofile.write((char*) &d,sizeof(data));
ofile.close();
}
void view()
{
clrscr();
data d;
ifstream ifile;
ifile.open("Data",ios::binary);
while(ifile.read((char*) &d,sizeof(data)))
{
d.showdata();
cout<<"\n\n";
}
getch();
}