What does the statement string::npos mean here
found=str.find(str2);
if (found!=string::npos)
cout << "first 'needle' found at: " << int(found) << endl;
What does the statement string::npos mean here
found=str.find(str2);
if (found!=string::npos)
cout << "first 'needle' found at: " << int(found) << endl;
It means not found.
It is usually defined like so:
static const size_type npos = -1;
It is better to compare to npos instead of -1 because the code is more legible.
found will be npos in case of failure to find the substring in the search string.
string::npos is a constant (probably -1) representing a non-position. It's returned by method find when the pattern was not found.
std::string::npos is implementation defined index that is always out of bounds of any std::string instance. Various std::string functions return it or accept it to signal beyond the end of the string situation. It is usually of some unsigned integer type and its value is usually std::numeric_limits<std::string::size_type>::max () which is (thanks to the standard integer promotions) usually comparable to -1.
The document for string::npos says:
npos is a static member constant value with the greatest possible value for an element of type size_t.
As a return value it is usually used to indicate failure.
This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.
$21.4 - "static const size_type npos = -1;"
It is returned by string functions indicating error/not found etc.