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;
}

Recommended Answers

All 2 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.