C++中string.find()的误用

来源:互联网 发布:谷歌娘软件下载 编辑:程序博客网 时间:2024/06/08 08:06


下面的结果是什么?


  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     string s = "abc";  
  8.     if(s.find("x"))  
  9.     {  
  10.         cout << "yes" << endl;    
  11.     }  
  12.     else  
  13.     {  
  14.         cout << "no" << endl;     
  15.     }  
  16.   
  17.     return 0;    
  18. }  

结果是:yes,因为s.find("x")的结果是(U32)(-1), 是一个很大的数,字符串查找时需要与s.npos进行比较。

if语句改为下面的就可以了:

if (s.npos != s.find("x"))


原创粉丝点击