<分区>
好吧,我对此有点陌生,如果我的问题看起来很愚蠢,我深表歉意。
基本上,我正在尝试将二进制文件读入字符串。
代码:
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();
编译它给我以下错误:
HangMan.exe 中 0x0FABDF58 (msvcp120d.dll) 处的未处理异常:0xC0000005:访问冲突读取位置 0x052DE6EC。
但是它确实会在抛出错误之前将字符串打印到控制台。
写入文件不会导致任何类型的错误,但读取 char[] 也不会。只有在读入字符串时才会出现此问题。
编辑:
我知道将 string* 转换为 char* 不是一个好主意,但我现在明白了。只是下面的代码有效,所以我假设使用字符串也有效:
#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;
}
如果我没理解错,这应该行不通,对吗?
@Rakibul Hasan:我检查了两个问题,没有重复。