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


此处只保存了对象的一个数据成员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;
}
类的成员变量写如文件的时候,最好不要用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;
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!