当以了一个类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;
}