Using the find method of the string class and I’m not getting the correct results in my query. Here is my code
int main()
{
string phoneData;
string name;
string phoneNumbers[51];
ifstream inputFile;
inputFile.open("phonebook");
int i = 0;
while (getline(inputFile, phoneData))
{
phoneNumbers[i] = phoneData;
i++;
}
cout << "Enter a name or partial name to search for: ";
getline(cin, name);
cout << endl << "Here are the results of the search: " << endl;
for(int i =0;i<50;i++)
{
if (name.find(phoneNumbers[i]) == 0)
cout << phoneNumbers[i] << endl;
}
inputFile.close();
return 0;
}
you aren’t using it correctly. string::find() returns the beginning position when it finds a match, or string::npos if it doesn’t find a match. you also have the search backwards. you’re looking for ‘name’ inside ‘phoneNumbers[i], not the other way around. your check inside the loop should look like this: