我对这段代码有问题。我的 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)
但是我在“打印一个”句子中没有看到任何“=”
阅读参考资料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.