Add or Subtract from a total based on first character

Hello, I am trying to use the following function to search an array of structs, however it doesn't seem to be working and it is returning the same thing no matter what I search... which is 15.

I am trying to return the number of the value of the array while searching for the name of the item.

1
2
3
4
5
6
  int search(Tools inventory[], string name, int length) {
	int loc = -1;
	for (int i = 0; i < length && loc != -1; i++)
		if (inventory[i].name == name)
			loc = i;
	return loc;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (userChoice == 'E') {
		string userProduct, posOrNeg, editValue;
		int spotInArray, currentInv, amountToChange;
		cout << "Enter product:";
		cin >> userProduct;
		cout << "Enter amount to add (+) or subtract (-):";
		cin >> editValue;

		posOrNeg = editValue.substr(0, 1);
		amountToChange = std::stoi(editValue.substr(1, 3));

		spotInArray = search(inventory, userProduct, 100);
		currentInv = inventory[spotInArray].amount;
		if (posOrNeg == "+") {
			inventory[spotInArray].amount = currentInv + amountToChange;
		}
		if (posOrNeg == "-") {
			inventory[spotInArray].amount = currentInv - amountToChange;
		}
		cout << "Item " << userProduct << " has new amount in stock " << inventory[spotInArray].amount;

	}
closed account (SECMoG1T)
your loop never runs:
1
2
3
4
5
6
int loc = -1;;//this is your error

for (int i = 0; i < length && loc != -1; i++);// terminates because loc == -1
		if (inventory[i].name == name)
			loc = i;
Last edited on
Duh!!! Thank you so much!
Topic archived. No new replies allowed.