c++ std:: string.Find以布尔表达式返回意外结果
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
返回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/相关文章:
- 为什么这会返回意外值?
- 从 C++ 调用 cURL 命令会返回意外的错误代码,如 1792 和 6656
- C++ 三角函数返回意外值
- 裸__declspec上的 memcpy 返回意外的字节
- 在C 中读取二进制文件会返回意外值
- OpenCL - 内核方法返回意外结果
- C :Bool方法在COUT语句之后返回意外数字
- 数组中的线性搜索返回意外结果
- POW函数为什么返回意外值
- std::min_element 从类对象返回意外结果
- 位NOT运算符返回意外的负值
- std::min_element返回意外结果
- 递归返回意外输出
- C++随机字符串返回意外结果
- 在DLL的基地址处Win API ReadProcessMemory返回意外数据
- OpenCV 'sortIdx' 返回意外结果
- find_if() 在 const 函数中返回意外的迭代器类型
- c++方法有时会返回意外的高值
- 函数返回意外的结构值
- c++ std:: string.Find以布尔表达式返回意外结果