先看一个bug:
string str = "csdn";
unsigned int i = str.find("-");
if (i < 0)
{
cout << "Not Found";
}
else
{
cout << "Found";
}
bug在于,unsigned int不可能<0,所以这段代码一定都会走到else。常见的正确写法大家都知道:
string str = "csdn";
int i = str.find("-");
if (i < 0)
{
cout << "Not Found";
}
else
{
cout << "Found";
}
但实际上string::find的返回值真的是unsigned
string str = "csdn";
auto i = str.find("-");
cout << typeid(i).name() << endl;
这里,string::find不存在时,返回的实际上是string::npos,所以标准写法应该是:
string str = "csdn";
if (str.find("-") == string::npos)
{
cout << "Not Found\n";
}
else
{
cout << "Found\n";
}