在数组中搜索字符串

时间:2013-09-19 06:01:53

标签: c++ arrays string search struct

我在“库存”数组中有“项目”,库存数组是由几个不同部分组成的结构,但我希望能够仅使用项目名称搜索数组的某个部分(所以我可以使函数删除,购买等。)我想知道如何这样做,如果它需要更容易将结构转换为类。请记住,它仍然是一项正在进行的工作,但我目前专门针对removeItem函数。在此先感谢您的帮助!

我的代码在这里:

#include "integerstore.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void removeItem(Item);
int buyItem(Item, int);
int sellItem(Item, int);
void stockReport(Item);

struct Item
{
string name;
float cost;
float price;
int quantity;
};

int main()
{
Item inventory[100];
int total = 0;
string cmd;

cout << "Welcome to inventory management. To add a new inventory item type add, to remove and item from inventory type remove, to add to inventory quantity type buy, to mark a sold item type sell, to see the current inventory report type report and to end the program type stop" << endl;

do
{
    cin >> cmd;

    if (cmd == "add") 
    {
        cout << "Enter the new item's name";
        cin >> inventory[i].name;
        cout << endl;
        cout << "Enter the new item's cost";
        cin >> inventory[i].cost;
        if (inventory[i].cost <= 100.00)
        {
            break;
        }
        else
        {
            cout << "Cost of item may not exceed 100.00, please reenter.";
            cin.clear();
        }
        cout << endl;
        cout << "Enter the new item's selling price";
        cin >> inventory[i].price;
        if (inventory[i].price <= 100.00)
        {
            break;
        }
        else
        {
            cout << "Selling price may not exceed 100.00, please reenter.";
            cin.clear();
        }
        cout << endl;
        i++;
    }
    else if (cmd == "remove") 
        removeItem(inventory[100]);

    else if (cmd == "buy") 
        buyItem(inventory[100], total);

    else if (cmd == "sell") 
        sellItem(inventory[100]);

    else if (cmd == "report") 
        stockReport(inventory[100]);

    else if (cmd != "stop") 
        cout << "invalid";
}
while (cmd != "stop");

system ("pause");
return 0;
}


int buyItem(Item w, int w2)
{
string itemName;
cout << "Enter the item name of which you wish to add more stock to" << endl;
cin >> itemName;


}

int sellItem(Item x, int x2)
{

}

void removeItem (Item y)
{
string itemName;
cout << "Enter the item name you wish to remove from the inventory" << endl;
cin >> itemName;
}


void stockReport(Item z)
{

}

1 个答案:

答案 0 :(得分:2)

您可以使用map<string, Item>(您可能希望从name结构中删除Item

然后您可以使用它,例如:

map<string, Item> inventory;
// Add
inventory["stuff"].cost = 12;
// ...
// Get
string name;
cin >> name;
Item myItem = inventory[name];