Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does string::npos mean? [duplicate]

Tags:

c++

what does the following statement mean?

    string s="Joe Alan Smith"";
    cout << (s.find("Allen") == string::npos) << endl; 
like image 362
sap Avatar asked Mar 17 '26 20:03

sap


2 Answers

Actually string::find() returns the position of the found string, but if it doesn't find the given string, it returns string::npos, where npos means no position.

npos is an unsigned integral value, Standard defines it to be -1 (signed representation) which denotes no position.

//npos is unsigned, that is why cast is needed to make it signed!
cout << (signed int) string::npos <<endl; 

Output:

-1

See at Ideone : http://www.ideone.com/VRHUj

like image 91
Nawaz Avatar answered Mar 19 '26 11:03

Nawaz


http://www.cplusplus.com/reference/string/string/npos/

As a return value it is usually used to indicate failure.

In other words, print out if the string 'Allen' was not found in the given string s.

like image 27
Amber Avatar answered Mar 19 '26 12:03

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!