Searching for string in structure array

Hi

I can't get the search function in my code to work. When I type of string to search, it just does nothing at all.
Any help to why it does nothing?


#include <iostream>
#include <string>
using namespace std;

struct data
{
string lname;
string fname;
int birthmonth;
int birthday;
int birthyear;
};

//function prototype
void getData(data &, int );
void showData(const data &, int);
int searchByLastName(const data &, string);

int main()
{
const int NUM_PLAYER = 2;
data player[NUM_PLAYER];
data p2[NUM_PLAYER];

int i;

cout << "Enter the 10 soccer players data:" << endl << endl;

for (i = 0; i < NUM_PLAYER; i++)
{
getData(player[i], i);
}

int choice;

while(choice != 6)
{
cout << "Enter 1 to input data, 2 to display original data, 3 to sort data \n";
cout << "4 to display sorted data, 5 to search by last name, 6 to exit the program: ";
cin >> choice;
cin.ignore();
cout << endl;

if (choice == 1)
{
for (i = 0; i < NUM_PLAYER; i++)
{
getData(player[i], i);
}
}

else if (choice == 2)
{
for (i = 0; i < NUM_PLAYER; i++)
{
showData(player[i], i);
}
}

else if (choice == 3)
{
for (i = 0; i < NUM_PLAYER; i++)
{
p2[i].lname = player[i].lname;
}
}


else if (choice == 5)
{
string look;
cout << "Enter part of last name to search: ";
cin >> look;

for (i = 0; i < NUM_PLAYER; i++)
{
int getNames = player[i].lname.find(look, 0);
if (getNames > 0)
{
cout << player[i].lname << endl;
}
}
}

cout << endl;
}

}

void getData(data &p, int j)
{
cout << "Last name for player " << (j + 1) << ": ";
getline(cin, p.lname);

cout << "First name for player " << (j + 1) << ": ";
getline(cin, p.fname);

cout << "birth month (2 digit format) for player " << (j + 1) << ": ";
cin >> p.birthmonth;
cin.ignore();

cout << "birth day (2 digit format) for player " << (j + 1) << ": ";
cin >> p.birthday;
cin.ignore();

cout << "birth year (4 digit format) for player " << (j + 1) << ": ";
cin >> p.birthyear;
cin.ignore();

cout << endl;
}

void showData(const data &p, int j)
{
cout << "Player " << (j + 1) << " data:" << endl;
cout << p.lname << endl;
cout << p.fname << endl;
cout << p.birthmonth << endl;
cout << p.birthday << endl;
cout << p.birthyear << endl;
cout << endl;
}
1
2
3
4
5
6
7
8
9
for (i = 0; i < NUM_PLAYER; i++)
{
  int getNames = player[i].lname.find(look, 0);
  if (getNames > 0)
    {
       cout << player[i].lname << endl;
    }
  }
}

What's basically happening is the function find( ) is returning the position of the first match. If you enter "Smith" as a last name and then proceed to search "Smith" it finds the match at the 0th position, returning the value 0, which then fails to pass if(getNames > 0) even though the match was found.

To compare the two strings, you can always just shove them together in an if( ).

if(player[i].lname == look)
Topic archived. No new replies allowed.