2

what does the following statement mean?

    string s="Joe Alan Smith"";
    cout << (s.find("Allen") == string::npos) << endl; 
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
sap
  • 1,141
  • 6
  • 41
  • 62

3 Answers3

15

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

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.

Amber
  • 507,862
  • 82
  • 626
  • 550
2

The .find() method returns string::npos if it did not find the target string within the searched string. It is an integer whose value cannot represent a "found" index value, usually -1. A valid index value is an integer >= 0 which represents the index at which the target string was found.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285