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

我对这段代码有问题。我的 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;
  }
}

输出 :

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

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

回答

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

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

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

  • To be accurate `std::string::npos` is not equal to -1 as it is unsigned

以上是我不明白为什么我的.find函数不起作用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>