Hello.
Our current assignment in C++ class involves reading/writing strings to file in binary format. Our professor has his own string class which we can use, but I've decided to use std::string. This is my first experience with binary files, so I'm trying to figure out how it works. Here is a small program that I wrote to better understand it:
Code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string name, take;
cout << "Enter name: ";
cin >> name;
ofstream fout("FFF.dat", ios_base::out | ios_base::binary);
fout.write(reinterpret_cast<char*> (&name), name.size()+name.capacity());
fout.close();
take.reserve(name.capacity());
take.resize(name.length());
ifstream fin("FFF.dat", ios_base::in | ios_base::binary);
if(fin.is_open()){
fin.read(reinterpret_cast<char*> (&take), name.size()+name.capacity());
}
fin.close();
cout << take << endl;
return 0;
}
It seems that it writes the string to file and is able to read it, but if name is larger than 15 chars it crashes after it outputs take. Does anyone know what I'm doing wrong, or if there is a better way to do this? I'm guess that I'm not getting the correct size of the string object, or that there may be virtual functions in string that are causing problems. any suggestions?