tags:

views:

92

answers:

6

What does the statement string::npos mean here

found=str.find(str2);

if (found!=string::npos)
    cout << "first 'needle' found at: " << int(found) << endl;
+2  A: 

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.

Brian R. Bondy
Thanks all for this info...
iSight
+1  A: 

found will be npos in case of failure to find the substring in the search string.

Raghuram
+5  A: 

string::npos is a constant (probably -1) representing a non-position. It's returned by method find when the pattern was not found.

Sheldon L. Cooper
+1 for actually showing the npos = no-pos derivation that makes it easy to remember. It's so obvious you wouldn't think about it once you knew it, but for someone seeing those letters for the first time it may not click...?
Tony
+1  A: 

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.

wilx
+2  A: 

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.

codaddict
+1  A: 
$21.4 - "static const size_type npos = -1;"

It is returned by string functions indicating error/not found etc.

Chubsdad