String.find始终返回true(C ++) [英] String.find returns true always (C++)

查看:154
本文介绍了String.find始终返回true(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让boolean found_word如果找到单词/字符则返回true,否则返回false,但是无论我在文本中写什么,它总是返回true.循环本身有效,已经尝试过了.包括IOStream和字符串.

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--;
}

有什么建议吗?

推荐答案

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

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

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

0,即false,仅当在索引0处找到子字符串时才返回.

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

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

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

这篇关于String.find始终返回true(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆