0

I'm trying to write objects that contaings strings into files and after that wants to read this information into objects. It's works fine until the end of program. As I understand error in strings. Program doesn't with this type. If I change them to array of chars it works. Can I work with strings in this program&

#include <iostream>
#include <Windows.h>
#include <fstream>
#include <string>
using namespace std;

class FileWorkers;
class Workers;

class Worker
{
protected:
    string name;
    string date_of_birth;
    string post;
public:
    Worker(string post = "Loader") : name(""), date_of_birth(""), post(post) {}
    virtual Worker& SetWorkerInfo(string name, string date_of_birth)
    {
        Worker::name = name;
        Worker::date_of_birth = date_of_birth;
        return *this;
    }
    virtual void ShowInfo()
    {
        cout << "Firstname and lastname: " << name << endl;
        cout << "Date of birth: " << date_of_birth << endl;
        cout << "Post:" << post << endl;
    }
    friend ostream& operator<<(ostream&, FileWorkers&);
}loader;
int size_worker = sizeof(Worker);

class FileWorkers
{
    string flname;
    fstream* fl;
public:
    FileWorkers(string flname)
    {
        FileWorkers::flname = flname;
        fl = new fstream();
    }
    ~FileWorkers() {
        fl->close();
        delete fl;
    }
    bool Newfl()
    {
        fl->open(flname, ios::in | ios::out | ios::trunc);
        if (!fl) return false;
        return true;
    }
    bool Readfl(Worker& worker)
    {
        fl->read(reinterpret_cast<char*>(&worker), size_worker);
        if (fl->good()) return true;
        fl->clear();
        return false;
    }
    void Rewfl()
    {
        fl->seekg(0);
        fl->seekp(0);
    }
    void Addfl(Worker worker)
    {
        fl->write(reinterpret_cast<char*>(&worker), size_worker);
        fl->flush();
    }
    string Getflname()
    {
        return this->flname;
    }
};

ostream& operator<<(ostream& out, FileWorkers& fw)
{
    Worker w;
    fw.Rewfl();
    while (fw.Readfl(w)) out << w.name << ' ' << w.date_of_birth << ' ' << w.post << endl;
    return out;
}

int main()
{
    FileWorkers fw("workers.txt");
    if (!fw.Newfl())
    {
        cout << "Error creating file";
        return 1;
    }
    int quan_workers = 1;
    string name, date_of_birth;
    for (int i = 0; i < quan_workers; i++)
    {
        cin >> name >> date_of_birth;
        fw.Addfl(loader.SetWorkerInfo(name, date_of_birth));
    }
    cout << fw << endl;
}

I really don't know how to solve this problem. Yeah, I can change to array of chars, but I want work with string, because it's much easier. Btw, sry for my bad english.

  • You can't use `reinterpret_cast` with a non-pod structure, you'll need to write a proper serialiser or use a serialisation library – Alan Birtles Nov 12 '22 at 08:42

0 Answers0