What does string::npos mean in this code?

boom picture boom · Sep 30, 2010 · Viewed 138.6k times · Source

What does the phrase std::string::npos mean in the following snippet of code?

found = str.find(str2);

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

Answer

Brian R. Bondy picture Brian R. Bondy · Sep 30, 2010

It means not found.

It is usually defined like so:

static const size_t npos = -1;

It is better to compare to npos instead of -1 because the code is more legible.