【问题标题】:c++ std::string.find returns unexected result in boolean expression [duplicate]c++ std::string.find 在布尔表达式中返回意外结果[重复]
【发布时间】:2017-03-16 15:51:50
【问题描述】:

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

【问题讨论】:

标签: c++ string boolean posix


【解决方案1】:

这是今天才被问到的。

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

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

【讨论】:

    【解决方案2】:
    bool test1 = a.find( ".." ) != std::string::npos;
    

    http://www.cplusplus.com/reference/string/string/find/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 2012-05-17
      • 2017-02-05
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多