Archived

This topic is now archived and is closed to further replies.

Hamlet

Help with streams

Recommended Posts

I am working on a project in which I need to create a class called Student which has various data members and functions One of the functions must be able to write the Student information to a file, (im using ios::binary file) and the other must be able to read from that file. I should mention i need to be able to edit the data in the file delete the data in the file. I am running into a problem. For this assignment we had to create our own String class. In the Student class we had to declare the name, SSN, and major as Strings(the ones we created). I cant figure out how to write the function in the string class to output (name, SSN, major) it to a data file created by my student class and then be able to read it back. Here is what i have for the write funcition in the student class. void student::writedata(student a) { ofstream recordout("record.dat", ios::out); if( !recordout ) { cerr << "File could not be opened. " < (&a), sizeof(student)); name.stringout(name, recordout); ssn.stringout(ssn, recordout); major.stringout(major, recordout); //recordout.write(reinterpret_cast (&schedule[10]), sizeof(classrec)); } here is the read data for student: void student::readdata() { ifstream recordin("record.dat", ios::in); if( !recordin ) { cerr << "File could not be opened. " < (&me), sizeof(student)); name.stringin(name, recordin); ssn.stringin(ssn, recordin); major.stringin(major, recordin); //recordin.read(reinterpret_cast (&sched[10]), sizeof(classrec)); me.showdata(); } here are the string functions i wrote to write the Strings to the file: void String::stringout(String &a, ostream &recordout) { recordout.write( a.sptr, sizeof(String)); } void String::stringin(String &a, istream &recordin) { recordin.read( a.sptr , sizeof(String)); } I have no compiling errors but when i run the exe and try to pull the info back from the file i get an error that says "debug assertion failed." anyone have any ideas or links? "... thats the rub...

Share this post


Link to post
Share on other sites
Ok let me be more specific.

How do you get a user defined type that you output to a file(losing type info) to be read back in so that the program knows what type it goes into?

"... thats the rub...

Share this post


Link to post
Share on other sites
You know which types you wrote, so you know which types to read. You don''t need to be able to dynamically determine type for this application.

I think your problem is that you''re using read and sizeof on a string. If a string is a class that contains a pointer to an array of characters, it simply won''t work as not all the data is stored ''in'' the class. You will have to write some sort of special output function that writes out the parts of a string individually.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions ]

Share this post


Link to post
Share on other sites