Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string::find not working as expected in c++

Tags:

c++

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?

like image 980
sop Avatar asked Mar 18 '15 16:03

sop


2 Answers

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)
like image 190
emlai Avatar answered Oct 12 '22 23:10

emlai


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;
}
like image 39
Neil Kirk Avatar answered Oct 13 '22 00:10

Neil Kirk