String.find始终返回true(C ++) [英] String.find returns true always (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_word
是false
,我个人保证!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屋!