字符串.输入返回true始终(C )

String.find returns true always (C++)

本文关键字:始终 true 输入 返回 字符串      更新时间:2023-10-16

im试图让boolean找到的dust_word返回true,如果它找到单词/字符,如果没有找到词,但是无论我在文本中写了什么,它始终返回true。循环本身有效,已经尝试过。包括iostream和字符串。

while(timestorun){
    found_word = text.find("khgdawjugfdjhawbdjkhsadgawkdsa");
    if(found_word){
        cout << "FOUND!!!" << endl;
    }
    else if(!found_word){
        cout << "Found problem!!!!!"<< endl;
    }
    timestorun--;
}

有什么建议?

您应该与npos进行比较。find不返回布尔值。

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

0(即 false)才能在索引0找到子字符串时返回。

另外,您的第二个条件是多余的 - 如果found_wordfalse,我个人保证!found_word将为true

应该更像这样:

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如果单词不在那里,则应返回-1,否则它将返回字符串中的位置