output and input files don't work with class?

November 30, 2010 at 22:01:04
Specs: Macintosh
please if any body know what the wrong with this program

first i run this program and write into a file

#include <iostream.h>
#include <fstream.h>

class person {
private:
char name[40];
int age;
public:
void GetData() {
cout << "\nname : ";
cin >> name;
cout << "\nage : ";
cin >> age;
}
};

int main (int argc, char * const argv[]) {

person pers;
pers.GetData();

ofstream outfile("PERS.DAT", ios::binary);
outfile.write( (char*)&pers, sizeof(pers) );
return 0;
}
//////////////////////////////////

second : I run this one to read from that file that I wrote in the first program but it shows non for name
and 0 for age help me please if you can

#include <iostream.h>
#include <fstream.h>

class person {
private:
char name[40];
int age;
public:
void show_data() {
cout << "\n the name : ";
cout << name;
cout << "\n the age : " << age;
}
};
/////////////////////////////
int main (int argc, char * const argv[]) {
person pers;

fstream infile("pers.DAT", ios::binary);
infile.read( (char*)&pers, sizeof(pers) );

pers.show_data();

return 0;
}


See More: output and input files dont work with class?

Report •


#1
December 1, 2010 at 09:17:46
fstream infile("pers.DAT", ios::binary);
You don't pass ios::in, nor is this an ifstream. Chances are you're just not giving the object the required read permissions.

That said, this method of serializing objects only work if you don't care about cross-platform compatibility.

How To Ask Questions The Smart Way


Report •

#2
December 1, 2010 at 11:48:19
aa ok thank you its hard to see that you don't write i infront of ifstream when you are tired thank you so much

Report •

Related Solutions


Ask Question