【问题标题】:How I can avoid from duplication of products with same Product ID [closed]我如何避免重复具有相同产品 ID 的产品 [关闭]
【发布时间】:2020-01-16 17:28:02
【问题描述】:

如何避免在文件处理中重复具有相同产品 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;
    }   
}

【问题讨论】:

  • 你试过什么?哪里出错了?
  • 现在看看.....

标签: c++ file file-handling


【解决方案1】:

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

【讨论】:

  • 我不想在我的二进制文件中写入或打印重复的产品,
猜你喜欢
  • 2021-02-25
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
相关资源
最近更新 更多