我对这段代码有疑问。 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
但是我在“打印一个”的句子中没有看到任何“=”
最佳答案
阅读 std::string.find
的引用。
http://www.cplusplus.com/reference/string/string/find/
请注意,它说它返回查询的位置,或者如果没有,则返回 string::npos
,如果您继续执行,将会看到 string::npos = -1 = SIZE_MAX
。 (这是 size_t
数字空间中唯一未使用的数字,因为字符串可能具有从 0 一直到 SIZE_MAX-1
的索引)任何非零值整数强制转换为 true,因此您的语句将始终为 true。
更改以检查是否 find != string::npos
。
关于c++ - 我不明白为什么我的 .find 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66186769/