Click to See Complete Forum and Search --> : string find_first_of fails


stober
December 11th, 2002, 10:55 AM
why does this fail (VC6 on W2K)


#include <string>

int main()
{
string spath = "\\windows\\something";

if(spath.find_first_of("*?") >= 0)
{
// this is always true
// remove the wild cards
}
}


But this works ok:


#include <string>
int main()
{
string spath = "\\windows\\something";
int pos = spath.find_first_of("*?");
if(pos >= 0)
{
// remove the wild cards
}
}

jfaust
December 11th, 2002, 11:06 AM
find_first_of returns type of size_type, which looks like it's unsigned int. Of course it's always >= 0. In the second example, you are casting it to an int.

Jeff

Philip Nicoletti
December 11th, 2002, 11:34 AM
When using std::string search/find functions, if not found
a special value is returned ... string::npos

So your check should look like this :


#include <string>
#include <iostream>

int main()
{
std::string spath = "\\windows\\something";

if(spath.find_first_of("*?") != std::string::npos)
{
std::cout << "found wildcard" << std::endl;
}

// edit adding further clarification ...


int pos1 = spath.find_first_of("?*");
cout << "as an int : " << pos1 << endl;

string::size_type pos2 = spath.find_first_of("?*");
cout << "as a string::size_type : " << pos2 << endl;

cout << "string::npos = " << string::npos << endl;


return 0;
}