我不明白为什么我的 .find 函数不起作用

I don't get why my .find function don't work

我对这段代码有疑问。我的 userInput.find("=") if 语句始终为真:

std::string userInput;
while (1)
{
  std::cout << "> ";
  getline(std::cin, userInput);
  if (std::cin.eof())
  {
    std::cout << "Program Exit" << std::endl;
    return 0;
  }
  if (userInput == "exit")
  {
    std::cout << "Program exit" << std::endl;
    return 0;
  }
  if (userInput.find("="))
  {
    std::cout << "yes" << std::endl;
  }
}

输出:

./main
> print a
yes
> exit
> Program Exit

但是我在“打印 a”的句子中没有看到任何“=”

userInput.find() 不 return 一个 bool。如果找不到它,它将 return npos,并且您的检查将从 npos 构造一个布尔值,这将为 TRUE。

答案:明确检查npos

阅读 std::string.find 的参考资料。 http://www.cplusplus.com/reference/string/string/find/

注意它说的是 returns 查询的位置,或者如果 none、returns string::npos,如果您继续执行,将会看到 string::npos = -1 = SIZE_MAX. (这是 size_t 数字 space 中唯一未使用的数字,因为字符串可能具有从 0 一直到 SIZE_MAX-1 的索引)任何非零整数强制转换为真, 所以你的陈述永远是正确的。

更改以检查是否 find != string::npos