c++ - String.find 总是返回 true (C++)

标签 c++ boolean

我试图让 boolean found_word 在找到单词/字符时返回 true,如果没有找到则返回 false,但无论我在文本中写什么,它总是返回 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 不返回 boolean 值。

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

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

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

关于c++ - String.find 总是返回 true (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183784/

相关文章:

c++ - 使用 libcurl : it does not appear to get the entire page 时出现问题

php - 如何从查询字符串中获取 boolean 值?

c++ - 从三个 boolean 值创建一个整数作为 C++ 中的位

mysql - 将多个 "attributes"添加到 MySQL 数据库中的身份的最有效方法

java - 使用 Java 确定 3 条边是否构成有效三角形的程序

c++ - XCode4 中的 "inline Methods Hidden"选项。

c++ - 在 C++ 中分割字符串需要越来越多的时间,而行的长度大致相似

c++ - 从 vector 到 vector 的过滤操作

C# 等效于 c++ 中的 bool 运算符和 rhs

c++ - 如何在*成员被销毁后*在析构函数中执行一些代码