一点OK 2021-07-16 23:14 采纳率: 45.5%
浏览 159
已结题

_Pnext 是 0x11FF7E4 求解?

为什么会报错,引发了异常: 读取访问权限冲突。
_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;
}

```;
  • 写回答

1条回答 默认 最新

  • a_cainiaoTxl 2021-07-17 08:28
    关注

    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;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 2月5日
  • 已采纳回答 1月28日
  • 创建了问题 7月16日