AvidScifiReader
AvidScifiReader

Reputation: 279

String.find returns true always (C++)

Im trying to have the boolean found_word to return true if it finds the word/character and false if it doesn't, but it returns true ALWAYS, no matter what I write in the text. The loop itself works, already tried that. IOStream and string are included.

while(timestorun){
    found_word = text.find("khgdawjugfdjhawbdjkhsadgawkdsa");

    if(found_word){
        cout << "FOUND!!!" << endl;
    }
    else if(!found_word){
        cout << "Found problem!!!!!"<< endl;
    }
    timestorun--;
}

Any suggestions?

Upvotes: 3

Views: 18711

Answers (2)

Elliot Mendiola
Elliot Mendiola

Reputation: 31

it should be something more like this:

int main ()
{
    int found = text.find("some text");
    if (found != std::string::npos)
    {
        //do stuff if word is there
    }
    else
    {
        //do stuff when word isnt there
    }
}

text.find should return a -1 if the word isnt there, otherwise it returns the position in string that you found it

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258548

You're supposed to compare with npos. find doesn't return a boolean value.

found_word = text.find("khgdawjugfdjhawbdjkhsadgawkdsa") != std::string::npos;

0, which is false, would only be returned if the substring was found at index 0.

Also, your second condition is redundant - if found_word is false, I personally guarantee !found_word will be true.

Upvotes: 17

Related Questions