c++ std:: string.Find以布尔表达式返回意外结果

c++ std::string.find returns unexected result in boolean expression

本文关键字:返回 意外 布尔表达式 结果 Find std string c++      更新时间:2023-10-16

我正在尝试搜索'..',该字符串表示POSIX系统上的文件路径。我正在使用std::string.find(".."),它似乎找到了正确的索引,但在布尔表达式中没有正确计算。

例如:

#include <string>
#include <stdio.h>

int main( int argc, char *argv[] ) {
  std::string a = "abcd";
  int apos = a.find( ".." );
  bool test1 = a.find( ".." ) >= 0;
  bool test2 = apos >= 0;
  if ( test1 ) {
    printf( "TEST1 FAILED: %ld >= 0!n", a.find( ".." ) );
  }
  if ( test2 ) {
    printf( "TEST2 FAILED %d >= 0!n", apos );
  }
}
输出:

$ g++ test.cpp -o test
$ ./test 
TEST1 FAILED: -1 >= 0!
$ 

任何想法为什么a.find( ".." )在布尔表达式中不评估为-1 ?

这个问题今天刚刚被问到。

这是因为find返回npos,这是一个unsigned int,它是用-1初始化,但它的类型是unsigned int,所以它比0大。

您应该将find的结果与npos而不是-1进行比较。

bool test1 = a.find( ".." ) != std::string::npos;
http://www.cplusplus.com/reference/string/string/find/