I can not figure out how to do a binary search when the infile is loaded into a struct in array. I do not know how to correctly name the parameter within the search function. Below is the code I am using. See the underline comment for where I am trying to place the parameter. Thanks for the help.
Here is the struct:
1 2 3 4 5 6 7 8 9 10 11 12
struct inventory
{
public:
int item_number;
string item_description;
int quantity_in_warehouse;
int cost;
int sell_price;
};
The variable array for the struct is:
1 2 3
inventory list[4];
Below is the function I am trying to complete this search in:
//Call function to check if item number is in inventory infile
void add_cart()
{
//variables
int itemNumber;
int counter, pos;
ifstream infile;
ofstream outfile;
//open infile and outfile
infile.open("inventory1.txt");
outfile.open("inventoryAdd.txt");
//counter to enter infile into array called list
for (counter = 0; counter < 4; counter++)
{
infile>>list[counter].item_number
>>list[counter].item_description
>>list[counter].quantity_in_warehouse
>>list[counter].cost
>>list[counter].sell_price;
}
//create loop to check multiple inventory item number requests
do{
cout <<"Enter item number: ";
cin >> itemNumber;
//call function to search for item number
//Here is where I do not know how to correctly name the parameter
int pos = searchItemNumber(list.itemNumber, 4, itemNumber);
if (pos!=-1)
cout << "itemm number found";
else
cout << "Number not on List \n" << endl;
}while (pos!=-1);
};
//function to search for item number in the array
int searchItemNumber(constint list[], int listLength, int searchItem)
{
int first = 0;
int last = listLength - 1;
int mid;
bool found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == searchItem)
found = true;
elseif (list[mid] > searchItem)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
elsereturn -1;
}
#include <iostream>
usingnamespace std;
int main ()
{
bool c;
int polje [4], b;
cout << "Enter 4 numbers"<< endl;
for (int a=0; a<4; a++)
{
cin >> b;
polje [a]=b;
}
do
{
cout <<"Enter a number"<< endl;
cin >> b;
for (int a=0;a<4;a++)
{
if (polje[a]==b)
{ c=1; break; }
else
{c=0;}
}
if (c==1){
cout << "Number "<< b << " is in array!"<< endl;}
else {
cout << "Number "<< b << " is NOT in array!"<< endl;}
}while (b!=-1); //Just for test you insert whatever you need
system ("PAUSE");
}