Alright, I'm a bit new to this so apologies if my question seems stupid.
Basically, I'm trying to read from a binary file into a string.
The code:
using namespace std;
fstream words;
words.open("Data/words.bin", ios::binary | ios::in);
string s;
words.read((char*)&s, sizeof(string));
cout << s;
words.close();
Compiling this gives me the following error:
Unhandled exception at 0x0FABDF58 (msvcp120d.dll) in HangMan.exe: 0xC0000005: Access violation reading location 0x052DE6EC.
However it does print the string to the console before throwing up the error.
Writing to the file does not result in any sort of error though nor does reading a char[]. The problem only occurs when reading into a string.
EDIT:
I kind of knew that it isn't a good idea to cast string* to char* but I understand now. Its just that following code works, so I assumed using a string would also work:
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
class foo
{
private:
int X;
int Y;
int Z;
char C;
public:
foo(int x,int y,int z, char c): X(x), Y(y), Z(z), C(c){}
void display()
{
cout<<X<<endl<<Y<<endl<<Z<<endl<<C<<endl;
}
};
int main()
{
fstream out;
out.open("file.bin", ios::binary | ios::out);
foo var(1,2,3,'a');
out.write((char*)&var,sizeof(foo));
cout<<"var: \n";
var.display();
out.close();
cout<<"var2 before reading: \n";
foo var2(0,0,0,'z');
var2.display();
fstream in;
in.open("file.bin", ios::binary|ios::in);
in.read((char*)&var2,sizeof(foo));
cout<<"var2 after reading: \n";
var2.display();
return 0;
}
If I understand right, this shouldn't work either correct?
@Rakibul Hasan: I checked both the questions, not a duplicate.