C++ 如何避免重复使用具有相同产品ID的产品
如何在文件处理中避免重复使用相同产品ID的产品,请任何人告诉我代码 徖C++ 如何避免重复使用具有相同产品ID的产品,c++,file,file-handling,C++,File,File Handling,如何在文件处理中避免重复使用相同产品ID的产品,请任何人告诉我代码 徖 struct Product { int Pid; char Pname[55]; int balance; }; void AddProduct() { Product p; cout <<"\nProduct ID: "; cin>>p.Pid; cout <<"Product Name: "; cin>>
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,并再次调用该函数以再次输入数据。如果循环在文件末尾终止,请以写模式打开文件并将结构数据附加到文件。您尝试了什么?哪里出错了?现在看一看……我不想在二进制文件中写入或打印重复的产品,