Reputation: 165
I have a linear search algorithm set up to search through an array of class objects it works but the output does not match, when i search for a particular name in the array the 1st and third values int the array are found but the second value is not found.
below is my code thanks for your help.
int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
if (player[j].getLastName()==val)
return j ;
}
return 1 ;
}
void showinfo()
{
string search;
int found ;
cout << "Please Enter The Player's Last Name : " ;
cin >> search ;
found=linsearch(search);
if (found==1)
{
cout << "\n There is no player called " << search ;
}
else
{
cout << "\n First Name : " << player[found].getFirstName() << "\n" << "Last Name : " << player[found].getLastName() <<
"\n" << "Age : " << player[found].getAge() << "\n" << "Current Team : " << player[found].getCurrentTeam() <<
"\n" << "Position : " << player[found].getPosition() << "\n" << "Status : " << player[found].getStatus() << "\n\n";
}
cin.get() ;
menu() ;
}
Upvotes: 1
Views: 4095
Reputation: 638
do something like this... return any other integer like '-1' if not found
int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
if (player[j].getLastName()==val)
return j ;
}
return -1 ;
}
void showinfo()
{
string search;
int found ;
cout << "Please Enter The Player's Last Name : " ;
cin >> search ;
found=linsearch(search);
if (found == -1)
{
cout << "\n There is no player called " << search ;
}
[...]
Upvotes: 0
Reputation: 36630
The second element's index is identical to the value which flags the "not found" condition.
Use an invalid index like -1
to flag the "not found" condition:
int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
if (player[j].getLastName()==val)
return j ;
}
return -1;
}
and then check for -1
in the calling function:
if (found==-1)
{
cout << "\n There is no player called " << search ;
}
Upvotes: 2
Reputation: 227418
Because you are using the index of the second element as a "not found" code:
int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
if (player[j].getLastName()==val)
return j ;
}
return 1 ;
}
You should return something that cannot be an index, for instance -1
. Or better still, use std::find_if.
Upvotes: 6