LateNoon 2022-09-24 12:22 采纳率: 63.6%
浏览 16

C++io读写与读入'问题

主函数用write和read的时候就能读取正常,单一个read就读取错误,这是为什么

#include <iostream>
#include <fstream>
using namespace std;
class Person{
public:
    string name;
    int age;
    Person(string n,int a){
        name = n;
        age = a;
    }
    Person(){};
    ~Person(){};
    void toString(){
        cout<<"name:"<<name<<" age:"<<age<<endl;
    }
};
void writeB(){
    //导入头文件
    //创建对象
    ofstream ofs;
    //打开文件,判断是否打开
    ofs.open("e:\\a.txt",ios::out|ios::binary);
    if(ofs.is_open()){
        //写入文件
        Person p("syx",19);
        ofs.write((const char*)&p,sizeof (p));
    } else{
        cout<<"open file defluat"<<endl;
    }
    //关闭流
    ofs.close();
}
void readB(){
    ifstream ifs;
    ifs.open("e:\\a.txt",ios::in|ios::binary);
    if(ifs.is_open()){
        Person p;
        ifs.read((char *)&p,sizeof (p));
        p.toString();
    } else{
        cout<<"open file defluat"<<endl;
    }

    ifs.close();
}
int main() {
    writeB();
    readB();
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-09-24 12:32
    关注

    writeB会生成这个文件。只是readB的话,如果这个文件不存,就报错了

    评论

报告相同问题?

问题事件

  • 创建了问题 9月24日

悬赏问题

  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真
  • ¥15 关于#c语言#的问题,请各位专家解答!
  • ¥15 这个如何解决详细步骤
  • ¥15 在微信h5支付申请中,别人给钱就能用我的软件,这个的所属行业是啥?