String.find returns true always (C++)

14,801

Solution 1

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.

Solution 2

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

Share:
14,801
AvidScifiReader
Author by

AvidScifiReader

Updated on June 06, 2022

Comments

  • AvidScifiReader
    AvidScifiReader almost 2 years

    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?