0

The incrementStock function calls the "addProduct" function only if the sku string given in the argument matches with a member of the "inventory" array (the array is of type *Product and of size 50). I initialized the array to nullptr in the constructor. "num" is the increment number. When I test it and enter a valid sku to incrementStock, I get "no space" from the addproduct function.

void Supplier::addProduct(Product *p)
{
bool space = false;
int counter=0;
        while(!space && counter < inventory.size() )
        {
                if(inventory[counter] == nullptr )
                {
                        inventory[counter] = p;
                        space = true;
                }
        counter++;
        }

        if (!space)
        {
                cout << "no space" << endl;
        }

}


void Supplier::incrementStock(const string &sku, int num)
{
bool found = false;
        for( int i = 0; i < inventory.size(); i++ )
        {
                if( inventory[i] && sku == inventory[i]->getSKU())
                {
                        found=true;
                        addProduct(inventory[i]);
                        inventory[i]->setQuantity(inventory[i]->getQuantity() +num);
                }
        }

        if (found ==false)
        {
                cout << "not found" << endl;
        }
}
3
  • Why don't you just start with the inventory array of zero length, and just push_back() to add new items? That way you don't need to do all these searches and zero comparisons.. Commented Feb 28, 2014 at 2:24
  • 1
    addProduct always fills one new empty slot, even when given a product that's already present in inventory. Is this what you meant to do? If you call incrementStock 50 times for the same product, you'll fill all 50 slots. Commented Feb 28, 2014 at 2:25
  • @Igor Tandetnik: Thank you! the way you put it made me realize what I did wrong, I actually don't want to re-add the same member again like I wrote it. Commented Feb 28, 2014 at 2:32

1 Answer 1

1

Consider this loop:

    for( int i = 0; i < inventory.size(); i++ )

If you get a match for sku within this loop, it will add an extra copy of that item into inventory. That's a bit odd, but fine if you want multiple copies of the same pointer in inventory.

The problem is that after that iteration of the loop, the loop will continue, and it will also find the copy we just made, and see that it matches, and then make another copy again. This repeats until the array is full.

Sign up to request clarification or add additional context in comments.

1 Comment

right that makes sense, that's why I kept getting long pages of the message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.