Using different objects for input and output the above code is not working. Pls give suggestion ASAP.

#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
class sample
{
 int num;
 char name[20];
public:
 void read()
 {
  cout<<"\n enter name";
  gets(name);
  cout<<"enter the number";
  cin>>num;
 }
 void write()
 {
  cout<<"\n The name is"<<name<<endl;
  cout<<"\n The number is"<<num<<endl;
 }

};
int main()
{
 sample s1,s2;
 fstream file;

 file.open("d:/Arindam/samplearindam.txt",ios::in);
 
 cout<<"Enter the details"<<endl;
  s1.read();


 file.write((char *)&s1,sizeof(s1));
 file.close();

 cout<<"\n\n\nOUTPUT";
 file.open("d:/Arindam/samplearindam.txt",ios::out);
 file.seekg(0);
file.read((char *)&s2,sizeof(s2)); 
s2.write();
 file.close();
 return 0;
}

Edited 6 Years Ago by peter_budo: Please do not use CODE SNIPPED option to post question. Use FORUM THREAD!

Using different objects for input and output the above code is not working. Pls give suggestion ASAP.

The suggestion depends on what the code is supposed to do. Since you didn't tell us, what can we we suggest?

at least other than Never use gets() , for various reasons
1) see this
2) why use a bad C function when a good C++ command works better?

> file.read((char *)&s2,sizeof(s2));
Well scribbling all over the base of your object in the hope that it will land on your class private members is way too much to hope for.

You need to arrange proper access to this memory.

This article has been dead for over six months. Start a new discussion instead.