I've got a custom class that is as follows:
class course {
private:
string prefix;
int number;
string title;
int credits;
char grade;
public:
//Constructors
course();
course(string, int, string, int, char);
//Accessors
void set();
void print() const;
string get_prefix() const;
int get_number() const;
string get_title() const;
int get_credits() const;
char get_grade() const;
//Operators
bool operator < (course) const;
bool operator > (course) const;
course operator = (course);
bool operator == (course) const;
bool operator == (int n) const;
bool operator != (course) const;
};
//.... then in main
vector<course> cache; //holds courses in memory
vector<course>::iterator point; //points at the cache
course temp; //buffer
fstream file;//for file I/O
And I'm trying to do file input and output as follows:
cout << "Loading file..." << endl;
file.open("Courses.dat", ios::in | ios::binary);
file.clear();
file.read(reinterpret_cast<char *>(&temp), sizeof(temp));
while (!file.eof()) {
cache.push_back(temp);
temp.print();
file.read(reinterpret_cast<char *>(&temp), sizeof(temp));
}
file.close();
cout << "Saving to file..." << endl;
file.open("Courses.dat", ios::out | ios::trunc | ios::binary);
file.clear();
for(point = cache.begin(); point != cache.end(); point++) {
temp = *point;
temp.print();
file.write(reinterpret_cast<char *>(&temp), sizeof(temp));
file.clear();
}
file.close();
What's interesting is if I write and read pre-made data like below, it works:
course one("CSCI", 2012, "C++ Programming 2", 3, 'A');
course two("MATH", 2081, "Multiple Varible Calculus", 4, 'C');
course three("ENGL", 1022, "Composition 2", 3, 'B');
file.open("Courses.dat", ios::out | ios::trunc | ios::binary);
file.write(reinterpret_cast<char *>(&one), sizeof(one));
file.write(reinterpret_cast<char *>(&two), sizeof(two));
file.write(reinterpret_cast<char *>(&three), sizeof(three));
file.close();
//close program, open it again without writing that data
//load data into cache, and it displays correctly
.But if I use any custom data (AKA user-input) it saves correctly as far as I can tell, but if I try to load the data it crashes when it tries to display it - printing out random gibberish.
Can anyone spot any errors I missed in the file I/O routines? If need be I can post the entire source code.
Thanks in advance for wading through this post!