【问题标题】:strcasecmp. unsolvable error messagestrcasecmp.无法解决的错误信息
【发布时间】:2017-09-12 10:37:11
【问题描述】:
#include <strings.h>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main()
{
    string s = "test";
    if(strcasecmp(s, "TEST"))
        cout << "equals"<< endl;

    return 0;
}

关于如何使用 strcasecmp 需要帮助,当我尝试编译时,编译器一直显示错误消息

错误:无法将参数“1”转换为“std::string {aka std::basic_string}”为“const char*”到“int strcasecmp(const char*, const char*)”

【问题讨论】:

标签: c++ c++11


【解决方案1】:

strcasecmp 接受 const char*,而不是 std::string 作为参数。请改用strcasecmp(s.c_str(), "TEST"),或者首先让s 成为C 风格的字符串。

【讨论】:

    【解决方案2】:

    strcasecmp() 函数需要一个指向以 null 结尾的 char 字符串的指针,您不能将 std::string 直接传递给它。

    正确的使用方法应该是:

    strcasecmp(s.c_str(), "TEST")
    

    此外,您的程序中的代码看起来不正确,因为strcasecmp() 在字符串相等的情况下返回零。因此,您应该使用以下内容:

    if(strcasecmp(s, "TEST") == 0)
        cout << "equals"<< endl;
    

    【讨论】:

      【解决方案3】:

      这意味着 strcasecmp 期望 C 样式字符串(0 终止 char[])而不是 C++ string。您可以通过s.c_str() 获得一份。

      【讨论】:

        【解决方案4】:

        你可以试试

        strcasecmp(s.c_str(), "TEST")
        

        【讨论】:

        • 您不能将字符串转换为 char*
        【解决方案5】:

        strcasecmp() 函数在 C 国际标准中是 not specified。但是,strcasecmp()POSIX.1-20014.4BSD specifications 的一部分。

        在 Cygwin 下你甚至需要额外的一行

        #include <strings.h>
        

        让这个函数在你自己的代码中可用。

        为了让您的代码保持可移植性,我会放弃这个功能并自己重建它的功能:

        int StringCaseCompare (const std::string& s1, const std::string& s2)
        {
          if ( &s1 == &s2 )
            return 0;
        
          auto iter1 = s1.cbegin();
          auto iter2 = s2.cbegin();
          
          while ( iter1 != s1.cend() )
          {
            if ( iter2 != s2.cend() )
            {
              int cmp = int(std::tolower(*iter1)) - int(std::tolower(*iter2));
        
              if ( cmp != 0 )
                return cmp;
        
              ++iter2;
            }
            else
              return int(std::tolower(*iter1));
        
            ++iter1;
          }
        
          return -int(std::tolower(*iter2));
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-30
          • 1970-01-01
          • 1970-01-01
          • 2015-02-03
          • 2021-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多