Finding a string inside a string

Started by
2 comments, last by gpalin 20 years, 10 months ago
I've been working on a database program (in C++), which (so far) contains strings to represent names of songs in the database. I'm trying to include a method to search for songs with a user-input keyword. Here's the code I have for this particular method:

void Database::findSong(string keyword) {
    cout << endl;

    map< string, vector<Song> >::iterator artistIt = artists.begin();
    int i = 1;
    while (artistIt != artists.end()) {
        vector< Song >::iterator songIt = artists[artistIt->first].begin();
        while (songIt != artists[artistIt->first].end()) {
            if ((songIt->getTitle()).find(keyword)) { //this is the line in question

                cout << i << ". " << songIt->getTitle() << " (" << songIt->getArtist() << ")" << endl;
            }
            songIt++;
            i++;
        }
        artistIt++;
    }
}
I get no errors when I compile, and it runs without trouble, but the method dplays the whole database - not just the songs I'm looking for. Meaning, if I input a word common to a few songs (but not all of them), the program displays them all anyway. Does the code above need changing somehow? I've looked at it and looked at it, and it seems to me that it should work. Any suggestions? I've marked the line that supposedly does the searching. Grant Palin [edited by - gpalin on June 16, 2003 6:59:35 PM] [edited by - gpalin on June 16, 2003 7:01:04 PM]
Grant Palin
Advertisement
if ((songIt->getTitle()).find(keyword) != string::npos)
Perhaps you should look at what find() returns if it DOESN''T find the string.

How appropriate. You fight like a cow.
BeerHunter, thanks. That change worked just fine.

And Sneftel, thanks. I looked it up, and found out what it did. Thanks for the push there.

Grant Palin
Grant Palin

This topic is closed to new replies.

Advertisement