为什么会报错,引发了异常: 读取访问权限冲突。
_Pnext 是 0x11FF7E4。
把注释去掉,再把赵四那行注释掉就没问题,这是为什么!
#include <iostream>
using namespace std
#include<string>
#include<fstream>
class person
{
public:
person(){}
person(int ag,string na):age(ag),name(na){}
void show() { cout << this->age<<name; }
int age;
string name;
};
int main(int argc,char *argv[])
{
fstream fio;
//fio.open("C:\\Users\\hhh\\Desktop\\c嘎嘎file.txt", ios_base::in | ios_base::out | ios_base::binary|ios_base::app);
//if (!fio.is_open())
//{
// cout << "打开文件失败" << endl;
//}
//person zh(27, "赵t");
//fio.write((char*)&zh, sizeof zh);
//cout << "存入文件成功!";
//fio.close();
////person zhang;
person zh(27, "赵四");
fio.open("C:\\Users\\hmc\\Desktop\\c嘎嘎file.txt", ios_base::in | ios_base::out | ios_base::binary);
while(fio.read((char*)&zh, sizeof zh)&&!fio.eof())
{
cout << zh.age << zh.name<<" ";
}
fio.close();
fio.clear();
return 0;
}
```;
Person类里面有string成员,对string对象使用sizeof的结果是string类型固有部分的大小,也就是不管string对象包含的字符串是什么,sizeof的结果都是一样的(我这里是44)。所以fio.write((char*)&zh, sizeof zh)这样的代码肯定不对。改成用文本模式输出到文件试试,以下供参考:
#include <iostream>
#include<string>
#include<fstream>
using namespace std;
class person
{
public:
person() {}
person(int ag, string na) :age(ag), name(na) {}
void show() { cout << this->age << name; }
int age;
string name;
};
int main(int argc, char *argv[])
{
fstream fio;
//fio.open("C:\\Users\\hhh\\Desktop\\c嘎嘎file.txt", ios_base::in | ios_base::out | ios_base::binary|ios_base::app);
fio.open("1.txt", ios_base::out);
if (!fio.is_open())
{
cout << "打开文件失败" << endl;
}
person p(27, "赵t");
fio << p.age << '\t' << p.name << endl;
cout << "存入文件成功!";
fio.close();
////person zhang;
person zh(27, "赵四");
//fio.open("C:\\Users\\hmc\\Desktop\\c嘎嘎file.txt", ios_base::in | ios_base::out | ios_base::binary);
fio.open("1.txt", ios_base::in);
while ((fio >> zh.age >> zh.name) &&!fio.eof() )
{
cout << zh.age << zh.name << " ";
}
fio.close();
//fio.clear();
return 0;
}