I am trying to verify if a specific string is in the input string and if so do something, based on the found string; but it seems that it is always doing the first task no matter what...
if (inputString.find(str1) >= 0)
{
//do something
}
else if (inputString.find(str2) >= 0)
{
// do something else
}
else
{
std::cout << "Strange" << std::endl;
}
It is always entering the // do something
block no matter if the str1
is present in 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;
}
it seems to work. Why is that? What am I doing wrong?
inputString.find(str1) >= 0
is always true.
This is because the return type of find
is size_t
which is an unsigned integer type, so it cannot be negative. Any decent compiler will give a warning for this comparison.
In your second example, when you convert the return value of find
to int
, if find
returned npos
, then the value becomes -1
. That's why >= 0
works there. But if find
returned a value greater than INT_MAX
but not npos
, the cast would turn the index to a negative value, and your logic would fail.
Therefore, you should compare to npos
instead:
if (inputString.find(str1) != std::string::npos)
std::string::find
returns std::string::npos
if the input string is not found. To check if the string contains your input string, you must use:
if (inputString.find(str1) != std::string::npos)
{
//do something
}
else if (inputString.find(str2) != std::string::npos)
{
// do something else
}
else
{
std::cout << "Strange" << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With