String.find () returns true when using == - 1, but false when using <0

I try to find a character inside a string, but get unexpected results. I understand that it string::find(char c)returns -1when it is not found. However, I get unexpected results.

Even if the string does not include '8', it still returns true.

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

//Output: Found

However, when used, 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
+4
source share
2 answers

I understand that it string::find(char c)returns -1when it is not found.

This is not accurate. According to the documentation :


npos, .

, , std::string::find std::string:: npos. , std::string::npos std::string::size_type, . -1, -1; . , s.find('8')<0 false, .

std::string:: npos:

static const size_type npos = -1;

, , size_type.

, std::string:: npos , .

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

if(s.find('8')==-1) , operator == , , ,

  • , , .

, -1 unsigned, std::string::npos, .

+7

string::find() size_t, unsigned int, .

+1

Source: https://habr.com/ru/post/1659680/


All Articles