samedi 25 janvier 2020

Problems with the For Loop That Checks if an Item of the same name exists already

Can someone explain to me why this isn't doing what I want it to do? I want the user to be able to input at least 5 items, however, I want to ensure that all items are unique. When they input the name of the item I want it to subsequently (check that there isn't another item already in there with the same name). I've got a (ranged based for loop) that iterates through the vector, however, when I put in two the same it doesn't loop back to the start it just continues, and for some reason it only checks and iterates through the vector once. Can someone please help me out? I've been working for hours trying to solve this.

bool Items::CheckIfItemExists(std::string &sInputName)
{
    for(const auto &Item : ItemsVec)
    {
        if (Item.GetItemName() == sInputName)
        {
            std::cout << "Item failed to add as there is already an item called that.\n";
            std::cin.clear();
            return false;
        }
    }
    return true;
}
void Items::AddNewItem()
{
    bool bValid = false;
    std::string sInputName;
    double dInputSalePrice = 0;
    int iInputQuantity = 0;
    do{
    std::cout << "Enter information for new item...\n";
    std::cout << "\tName: ";
    std::cin.ignore();
    std::cin.clear();
    std::getline(std::cin,sInputName);
    bValid = CheckIfItemExists(sInputName);
    }while(bValid == false);

    bool bSalePriceValid = false;
    do{
        std::cout << "\tSale price: £";
        std::cin >> dInputSalePrice;
        if(!std::cin)
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            std::cout << "\n";
            std::cout << "Sorry, invalid input input. Try again!\n";
            std::cout << "\n";
        }
        else
        {
            bSalePriceValid = true;
        }
    }while(bSalePriceValid == false);

    bool bQuantityValid = false;
    do{
        std::cout << "\tQuantity sold: ";
        std::cin >> iInputQuantity;
        if(!std::cin)
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
            std::cout << "\n";
            std::cout << "Sorry, invalid input input. Try again!\n";
            std::cout << "\n";
        }
        else
        {
            bQuantityValid = true;
        }
    }while(bQuantityValid == false);

    Item NewItem(sInputName, dInputSalePrice, iInputQuantity);
    ItemsVec.push_back(NewItem);
    std::cout << "You've succesfully added a new item.\n";

}

Aucun commentaire:

Enregistrer un commentaire