【问题标题】:String.find returns true always (C++)String.find 总是返回 true (C++)
【发布时间】:2012-10-22 10:28:26
【问题描述】:

我试图让 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--;
}

有什么建议吗?

【问题讨论】:

  • 您可以使用else { 代替else if(!found_word){。这不会改变您的代码的工作方式,但它更简洁一些。
  • 我不能,因为在真正的代码中还有相当多的 if/elses

标签: c++ boolean


【解决方案1】:

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

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

0,即false,只有在索引0 找到子字符串时才会返回。

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

【讨论】:

  • +1。特别是,string::npos(size_t)-1,这在布尔上下文中是正确的。
【解决方案2】:

应该是这样的:

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,否则返回您在字符串中找到它的位置

【讨论】:

  • 感谢修复,太习惯了 System::String(-1 替换了 Windows System C++ 版本 String 中的 std::string::npos)
猜你喜欢
  • 2013-08-06
  • 2017-05-10
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多