我试图验证输入字符串中是否存在特定字符串,如果是,则根据找到的字符串执行某些操作;但似乎无论如何它总是在做第一个任务......
if (inputString.find(str1) >= 0)
{
//do something
}
else if (inputString.find(str2) >= 0)
{
// do something else
}
else
{
std::cout << "Strange" << std::endl;
}
它总是进入// do something
阻止无论是否str1
存在于inputString
or not.
If I do
int str1pos = inputString.find(str1);
int str2pos = inputString.find(str2);
if (str1pos >= 0)
{
//do something
}
else if (str2pos >= 0)
{
// do something else
}
else
{
std::cout << "Strange" << std::endl;
}
似乎有效。这是为什么?我究竟做错了什么?
inputString.find(str1) >= 0
总是正确的。
这是因为返回类型find http://www.cplusplus.com/reference/string/string/find/ is size_t http://www.cplusplus.com/reference/cstddef/size_t/这是一个unsigned整数类型,所以不能为负数。任何像样的编译器都会对此比较发出警告。
在第二个示例中,当您转换返回值时find
to int
, if find
回npos http://www.cplusplus.com/string::npos,则该值变为-1
。这就是为什么>= 0
在那里工作。但如果find
返回的值大于INT_MAX
但不是npos
,强制转换会将索引变为负值,并且您的逻辑将失败。
因此,您应该比较npos
反而:
if (inputString.find(str1) != std::string::npos)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)