isquaredr isquaredr - 1 month ago 5
C++ Question

string.find() returns true when ==-1 is used but false when <0 is used

I am trying to find a character within a string but I am getting unexpected results. My understanding is that string::find(char c) returns -1 when it is not found. However, I am getting some unexpected results.

Even though the string does not include an '8', it is still returning true.

std::string s = "123456799";
if(s.find('8')<0)
cout << "Not Found" << endl;
else
cout << "Found" << endl;

//Output: Found


However, when using == instead the code works as expected.

std::string s = "123456799";
if(s.find('8')==-1)
cout << "Not Found" << endl;
else
cout << "Found" << endl;

//Output: Not Found

Answer

Note the return type of std::string::find is std::string::size_type, which is a unsigned integer type. s.find('8')<0 will always be false because it's not possible to be negative.

According to the documentation,

Return value
Position of the first character of the found substring or npos if no such substring is found.

you should use std::string::npos for checking the result:

if (s.find('8') == std::string::npos)
    cout << "Not Found" << endl;
else
    cout <<  "Found" << endl;

if(s.find('8')==-1) works fine, because the left-hand operand of operator== here is unsigned, the right-hand one is signed. According to the rules for arithmetic operators,

  • Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

So -1 will be onverted to unsigned, which is the exact value of std::string::npos and then works as expected.

Comments