太阳船鸟. 2022-04-10 22:14 采纳率: 100%
浏览 26
已结题

关于c++文件存储类对象不完整的问题

当以了一个类goods,在主函数外定义了一个全局对象m,利用对象函数m.inputinfor()对数据成员进行初始化,并用文件“goods.txt"储存,但是文件打开后信息储存不完整,请问如何解决;

部分代码附上:
[](

#define LEN sizeof(Goods)
fstream file;
Goods m;

void Goods::inputinfor()
{
    cout << "输入商品名称:";
    cin >> this->name;
    cout << "设置价格:";
    cin >> this->price;
    cout << "输入成本:";
    cin >> this->cost;
    profit = price - cost;
    cout << "添加成功!" << endl;
}

void addtype()            //主函数外的函数
{
    char again;    //接收后续输入
    file.open("goods.txt", ios::app | ios::binary); 
    if (file.fail()) { cout << "文件打开错误" << endl; exit(0); }
    do {
        m.inputinfor();   // 初始化m;
        file.write((char*)&m, sizeof(LEN));
        cout << "还要继续添加商品吗?(Y/N)" << endl;
        cin >> again;
        cin.ignore();
    } while (toupper(again) == 'Y');
    file.close();
}


```)


![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/637249995946182.png "#left")


![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/721079995946134.png "#left")

此处只保存了对象的一个数据成员name,price和cost都没有保存
调用对象的print函数输出没有问题

```c++

void Goods::print()
{
    cout << "**************************" << endl;
    cout << "商品名称:" << name << endl;
    cout << "商品价格:" << price << endl;
    cout << "商品库存:" << stock << endl;
    cout << "商品成本:" << cost << endl;
    cout << "商品利润:" << profit<< endl;
    cout << "商品销售量:" << sale << endl;
    cout << "**************************" << endl;
}

img

  • 写回答

2条回答 默认 最新

  • 关注

    类的成员变量写如文件的时候,最好不要用fwrite函数。
    把file.write((char*)&m, sizeof(LEN));改成:

    file << m.name << " " << m.price << " " << m.cost << " " << m.profit<<" ";
    
    

    如果一条商品信息一行的话,就把最后的""改成endl:

    file << m.name << " " << m.price << " " << m.cost << " " << m.profit<<endl;
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月23日
  • 已采纳回答 4月15日
  • 修改了问题 4月10日
  • 创建了问题 4月10日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度