如何避免重复具有相同产品 ID 的产品

How I can avoid from duplication of products with same Product ID

本文关键字:ID 何避免      更新时间:2023-10-16

如何避免在文件处理中重复具有相同产品ID的产品,请任何人都可以告诉我它的代码 ............................................................................................................................................................

struct Product
{
int Pid;
char Pname[55];
int balance;
};
void AddProduct()
{
Product p;
cout <<"nProduct ID: ";
cin>>p.Pid;
cout <<"Product Name: ";
cin>>p.Pname;
cout <<"Balance: ";
cin>>p.balance;
ofstream ofs("Products.bin");
ofs.write(reinterpret_cast<char *>(&p), sizeof(p));
ofs.close();
cout <<"nProduct Successfully Saved";
}
ProductOpt()
{
char ch;
while(1)
{
cout <<"n1. Add Product"<<endl;    
cout <<"2. Display All Products"<<endl;
cout <<"3. Modify Product"<<endl;
cout <<"4. Delete Product"<<endl;
cout <<"5. Back"<<endl;
ch = getch();
cout<<endl;
if(ch == '1')
AddProduct();       
else if(ch == '2')
DisplayProduct();
else if(ch == '3')
ModifyProduct();
else if(ch == '4')
DeleteProduct();
else if(ch == '5')
break;
else
cout <<"Invalid Option"<<endl;
}   
}

输入后,只需先以读取模式打开文件,运行循环直到文件末尾,并使用文件中存储的 ID 检查 Id。如果匹配,则打印它是重复的 Id,然后再次调用该函数以再次输入数据。如果循环在文件末尾终止,则以写入模式打开文件并将结构数据附加到文件中。