Linear Searching an array of class objects

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 particluar 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

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() ;
	
}
The second element of the array has the index equal to 1. But you are using this value as an indication that an object was not found. Also if the array contains 3 elements then your loop is incorrect.

Instead of

1
2
3
4
5
6
7
8
9
int linsearch(string val)
{
	for (int j=0; j <= 3; j++)
	{
		if  (player[j].getLastName()==val)
		 return j ;			
	}
		return 1 ;
}


it would be better to write

1
2
3
4
5
6
7
8
9
10
int linsearch( const string &val )
{
	int j = 0;
	for ( ; j < 3; j++)
	{
		if  (player[j].getLastName()==val)
		 return j ;			
	}
		return j ;
}



The indication of that a value is not found is return value equal to the size of the array.
Last edited on
thanks vlad got it working
Topic archived. No new replies allowed.