升级基于文本游戏的库存中的删除功能

时间:2017-12-14 00:58:22

标签: c++

我仍然是C ++的新手,但我目前正在研究基于文本的游戏。对于我的游戏,我有一个可用的库存,但我想添加几个函数,所以它更好。我试过谷歌搜索,但我找不到足够的帮助或资源让我自己能够做到这一点。

我要做的第一件事就是当我使用删除功能时。对于该功能,我让用户输入他们希望从库存中删除的项目。我希望能够检查用户是否输入了库存中存在的项目,而不是创建项目。因此,在用户输入项目之后,我接受该项目并浏览列表,检查它是否存在,然后如果存在,则将其删除,如果不存在则打印出错误消息。

到目前为止,这是我的代码:

void Inventory::DeleteItem()
{
    string deleteitem = " ";

    if (item_numbers == 0) {
        cout << "\nError: No items in the Inventory.\n\n";
    }
    else {
        cout << "\nPlease type the item you wish to use or take out of the inventory: ";
        cin >> deleteitem;
    }
    bool found = false;
    for (int i = 0; i<item_numbers && !found; i++) {
        if (Info[i].item_name == deleteitem) {
            while(found == true){
                cout<<"Found an item matching what you wrote: "<<Info[i].item_name<<endl;
                item_numbers--;
                cout<<"Item: "<<Info[i].item_name<< " is now gone." <<endl;
                break;
            }
        }
         if (found == false){
            cout<<"liar"<<endl;
            break;
            }

    }
}

我敢打赌解决方案很简单,我很想念它。老实说,我无法看到它。对不起!但我感谢所有的帮助!

目前,当我测试代码时,这就是它的打印方式:

Which item will you be adding to your inventory?  Here

Which item will you be adding to your inventory?  Now

Please type the item you wish to use or take out of the inventory: Here
liar

1 个答案:

答案 0 :(得分:0)

您无法以您认为的方式删除它。 我刚才做过类似的事情,我的建议是:  1.使用另一个课程&#34; Item&#34;使用属性&#34; Name&#34;和&#34; NumberOfItems&#34;(如果你愿意,可以更多);  2.在Inventory课程中添加属性&#34; vector<Items> MyItems&#34; (通过这种方式你也可以了解vector)  3.当您在列表中找到该对象时,请拨打MyItems.erase(position),其中position是您找到的项目的索引。