Hello!
How can I read a class object from a file that I have just written to.
The class
FunctionsCode:class Hired { private: int nr; int ant_barn; public: Hired (int n) { cout << "Hired nr: (100-999)" << endl; cin >> nr; cout << "Ant barn: 0-20" << endl; cin >> ant_barn; } Hired () { cout << "\n\nWARNING 1: SHALL NOT RUN THIS CONSTRUCTOR\n\n"; } void write_file(ofstream* out) { *out << nr << " "; *out << ant_barn << " "<< endl; } void display() { cout << "Nr: " << nr; cout << "ant barn: " << ant_barn; cout << endl << endl; } Hired(int nr, int b) { nr = nr; ant_barn = b; } int getnr() { return nr; } int getbarn() { return ant_barn; }
GLobals:Code:void read_file(ifstream* in, Hired* a) { int ii = 0; in.read((char*) &a, sizeof(Hired)); while (!in.eof()) { in.read((char*) &a, sizeof(Hired)); hired2[ii] = new Hired(a->getnr(), a->getbarn()); hired2[ii]->display(); ii++; } }
The main programme:Code://Globale variabler Hired* hired[MAX_ANS+1]; // Array with pointer. Hired* hired2[MAX_ANS+1]; // Array with pointer int lastused = 0;
SO; what this does (some things might not be here, because I've tried to minimize it, cutting out irrelevant code), it simply creates one object of the class "hired", puts the data from it (two int variables) into a text file.Code:int main() { hired[lastused] = new Hired(25); //Filling in data, at least 1 ofstream myfile("hired.dta", ios::out | ios::ate); int i=0; //Read to file for (i = 1; i <= lastused; i++) { hired[i]->write_file(&myfile); hired[i]->display(); } myfile.close(); //So far, so good... //Read the whole file, and put it back to memory ifstream myfile2("hired.dta", ios::in); Hired* a; Read_file(myfile2, a); cout << "DONE"; return 0; }
Now I want to read those two int variables back, and put it where it belongs (into an object of the class Hired).
Whats working: Writing to the textfile, putting all object data to it.
I've marked a red line... Where the erorr lies... I can compile this, but when running, just simply freezes when I reach the red lines...
PS: should I rather write to a binary file rather than ASCII?



LinkBack URL
About LinkBacks



