【发布时间】: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?
【问题讨论】:
-
启用更多编译器警告。具体来说,你应该对
error: comparison of unsigned expression >= 0 is always true [-Werror=type-limits]感兴趣。 -
因为
std::find的返回类型是无符号整数,所以不能为负数。见string.find() returns true when ==-1 is used but false when <0 is used