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

Soy*_*eko 2 c++ find getline

我对这段代码有问题。我的 if 语句userInput.find("=")总是正确的:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

输出 :

./main
> print a
yes
> exit
> Program Exit
Run Code Online (Sandbox Code Playgroud)

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

Qwe*_*ers 5

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

请注意,它说它返回查询的位置,或者如果没有,则返回string::npos,如果您继续执行将看到string::npos = -1 = SIZE_MAX。(这是size_t数字空间中唯一未使用的数字,因为字符串可能具有从 0 到 的索引SIZE_MAX-1)任何非零整数都会强制为真,因此您的陈述将始终为真。

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

  • 准确地说,`std::string::npos` 不等于 -1,因为它是无符号的 (2认同)