I'm trying to search for the presence of '..' in a string that represents a file path on a POSIX system. I'm using std::string.find(".."), and it seems to be finding the correct index, but is not evaluating correctly in boolean expressions.
For example:
#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 );
}
}
Output:
$ g++ test.cpp -o test
$ ./test
TEST1 FAILED: -1 >= 0!
$
Any ideas why a.find( ".." )
is not evaluating to -1 in the boolean expressions?
This has just been asked today.
It's because find
returns npos
which is an unsigned int
, it is initialized using -1
however it's type is unsigned int
, so that it is larger than 0
.
You should compare find
's result with npos
not -1
.