/* This program demonstrates the confusing nature of string::npos. */ #include #include #include #include using namespace std; int main() { string s; /* When find() fails, it return string::npos. Therefore, when you want to see if a find() calls has succeeded or failed, you should test against string::npos, as I do below: */ s = "ABCDEFG"; cout << (s.find("ABC") == string::npos) << endl; // This should print 1 = true. cout << (s.find("CBA") == string::npos) << endl; // This should print 0 = false. /* So, what exactly is string::npos? If you look up the documentation, it's of type std::string::size_type, which is an unsigned long. If you use cout to print it, you get a giant integer. As hex, it's 16 f's (all bits set to one). If you set it or typecast it to a signed long, it becomes -1. What to make of all of this? Just use "string::npos" when you want to test that a find() call has failed, and think smugly to yourself what a poor decision it was for find() to return a std::string::size_type... */ cout << "When you use cout, string::npos is " << string::npos << endl; cout << "When you use hex, string::npos is 0x" << hex << string::npos << endl; cout << "Using printf(\"%lu\"), you get: "; printf("%lu\n", string::npos); cout << "Using printf(\"%ld\"), you get: "; printf("%ld\n", string::npos); return 0; }