strcmp函数的使用

来源:互联网 发布:c语言建筑物高度 编辑:程序博客网 时间:2024/05/20 10:12



________________________________________________________________________________________________________________________________________________
strcmp("ha","he")是可以的。  
  但是如下代码:  
  string   str1   =   "ha";  
  string   str2   =   "he";  
  strcmp(str1,   str2);  
  会产生如下的ERROR:  
   
  error   C2664:   'strcmp'   :   cannot   convert   parameter   1   from   'class   std::basic_string<char,struct   std::char_traits<char>,class   std::allocator<char>   >'   to   'const   char   *'  
  No   user-defined-conversion   operator   available   that   can   perform   this   conversion,   or   the   operator   cannot   be   called  
   
  为什么呢?
 
  _______________________________________________________________________________________________________________________________________________
 
  int   strcmp(const   char*   str1,   const   char*   str2);  
  这个函数是C标准库的函数,处理的是C风格0结尾字符数组字符串。  
  C++标准库中的string类有可以直接使用的<,>,<=,>=,==,!=运算符,通常也用不到这个函数。  
 
  _______________________________________________________________________________________________________________________________________________
 
  对,   strcmp()处理的是C风格的字符串。  
  而你用的是string类,2者是不同的。
 
  _______________________________________________________________________________________________________________________________________________
  ***********************************************************************************************************************************************
  strcmp函数原型为:  
  int   strcmp(  
        const   char   *string1,  
        const   char   *string2    
  );  
   
  其参数是传统的char   *型字符串,string型数据类型是不能作为其参数的。但可以通过string成员函数string::c_str()转换成char*类型。象这样调用:  
  strcmp(str1.c_str(),   str2.c_str())  
 
  ***********************************************************************************************************************************************
  -----------------------------------------------------------------------------------------------------------------------------------------------