c++ std::string.find returns 布尔表达式中的意外结果

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

我正在尝试在代表 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 returns 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/