hello, im newbie in c++ and i have some newbie questions.
erm here's the problem ive been thinking :

#include <iostream>
#include <fstream>

using namespace std;

struct Info
{
    string name;
    int age;
};

int main()
{
    Info person1, person2;
    fstream writefile("output.txt", ios::out | ios::binary);

    person1.name = "sendy";
    person1.age = 18;

    writefile.write(reinterpret_cast<char*>(&person1), sizeof(person));
    writefile.close();

    fstream readfile("outputt.txt", ios::in | ios::binary);

    readfile.read(reinterpret_cast<char*>(&person2), sizeof(person2));

    cout<<"name = "<<person2.name<<endl;
    cout<<"age = "<<person2.age<<endl;

    readfile.close();

    return 0;

}

erm i already know that the problem is with the "person1.name" and "person2.name" because its a string class object, means its a pointer inside a structure which ive been trying to convert into a char*, some people said it would work if i used char arrays for person1.name and person2.name,
then i try to read more from my beginner c++ e-book , also search some keywords in google but i still havent got it how to convert pointer inside a structure into a char pointer..
how to fix this problem?

note : sorry if i ask alot, im just curios :D

Edited 4 Years Ago by Sendy Hipo

Unfortunately, this approach wouldn't work in any case, at least not in any consistent manner; this is because the integer component of the structure will, in many cases, have an offset to force it to align to a word boundary. This is a system-dependent and compiler-dependent behavior, and would cause the subsequent read() to fail as it would not know how large the alignment padding is.

What you really need to do is serialize the structure, that is to say, which is to say (in this case), you need to save the individual components separately. You may find it easier to do this in discrete functions rather than inside the main() function, just for modularity's sake:

const BUFFER_SIZE = 1024;

void writeInfo(std::fstream& fs, const Info& person)
{
    fs.write(person.name.c_str(), person.name.length() + 1);
    fs.write(reinterpret_cast<char *>(&person.age), sizeof(int));
}

void readInfo(std::fstream& fs, Info& person)
{
    char buffer[BUFFER_SIZE];
    char* p;
    int age;

    fs.read(buffer, BUFFER_SIZE - 1);
    buffer[BUFFER_SIZE - 1] = '\0';     // force-delimit the input
    person.name = buffer;

    p = buffer;
    while (*p != '\0')  // seek to the end of the name string
        p++;

    fs.seekg((p - buffer + 1), ios::cur);  // set the getpos to the integer value
    fs.read(reinterpret_cast<char *>(&age), sizeof(int));
    person.age = age;
}

Mind you, it may make sense to use a text value for the integer, here, as well; this would allow you to view the data in a standard text editor.

Edited 4 Years Ago by Schol-R-LEA

Comments
nice keep it up!
This question has already been answered. Start a new discussion instead.