0

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;
}
4
  • 4
    you need to finish your ques Commented Dec 13, 2012 at 18:00
  • 2
    I would expect that you need to use if(phoneNumbers[i].find(name) != std::string::npos) instead of name.find(phoneNumbers[i]) == 0 Commented Dec 13, 2012 at 18:01
  • 1
    Any reference would tell you what it returns. Commented Dec 13, 2012 at 18:10
  • Hahaha, just somebody. Yeah I'm not sure what happened there but I edited it. Must have been distracted. Commented Jan 12, 2013 at 6:04

2 Answers 2

3

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:

if (phoneNumbers[i].find(name) != string::npos)
    cout << phoneNumbers[i] << endl;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I had a hard time understanding the syntax of this method but now I understand. Thanks again!
Sorry I was busy with school work. It's finals week! But I didn't forget, I always come back and do the right things. Thanks again for clearing this up.
1

Change

if (name.find(phoneNumbers[i]) == 0)

to

if (phoneNumbers[i].find(name) != std::string::npos)

The former is trying to locate phoneNumbers[i] within name. The second (which I believe is what you intended) is searching for name within phoneNumbers[i]. Second, the failure return for std::string::find is std::string::npos not zero.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.