【问题标题】:Problems with the comparison of two strings using strcmp使用strcmp比较两个字符串的问题
【发布时间】:2013-10-11 14:44:20
【问题描述】:

我想比较 2 个字符串,但是当我执行 strcmp 函数时,它告诉我:

'strcmp' : cannot convert parameter 1 from 'std::string'

我该如何解决这个问题?

这是我的代码:

int verif_file(void)
{
    string ligne;
    string ligne_or;

    ifstream verif("rasphone");
    ifstream original("rasphone.pbk");
    while (strcmp(ligne, "[SynCommunity]") != 0 &&
        (getline(verif, ligne) && getline(original, ligne_or)));    
    while (getline(verif, ligne) && getline(original, ligne_or))
    {
        if (strcmp(ligne, ligne_or) != 0)
            return (-1);
    }

    return (0);
}

【问题讨论】:

  • 第一个while 循环做什么?它几乎什么都不做,对吧?
  • string 类被精确引入以避免 C str 函数 ;)

标签: c++ string comparison string-comparison strcmp


【解决方案1】:

您的编译器给您一个错误,因为 strcmp 是一个 C 风格的函数,它需要 const char* 类型的参数,并且没有从 std::stringconst char* 的隐式转换。

虽然您可以使用std::stringc_str() 方法检索这种类型的指针,但由于您使用的是std::string 对象,因此您应该使用运算符== em> 改为:

if (ligne == ligne_or) ...

或与const char*比较:

if (ligne == "[Syn****]") ...

【讨论】:

    【解决方案2】:

    我喜欢 boost 算法库。

    #include <boost/algorithm/string.hpp>
    
    std::string s1("This is string 1");
    std::string s2("this is string 2");
    
    namespace balg = boost::algorithm;
    
    // comparing them with equals
    if( balg::equals( s1, s2 ) ) 
         std::cout << "equal" << std::endl;
    else
         std::cout << "not equal" << std::endl;
    
    // case insensitive  version
    if( balg::iequals( s1, s2 ) ) 
         std::cout << "case insensitive equal" << std::endl;
    else
         std::cout << "not equal" << std::endl;
    

    【讨论】:

      【解决方案3】:

      只需使用std::stringoperator==

      if (ligne == "[SynCommunity]") ...
      
      if (ligne == ligne_or) ...
      

      【讨论】:

        【解决方案4】:

        如果你想用strcmp,那就试试

        if (strcmp(ligne.c_str(), ligne_or.c_str()) != 0)
           ...
        

        【讨论】:

          【解决方案5】:

          改变

          if (strcmp(ligne, ligne_or) != 0)
          

          if (ligne != ligne_or)
          

          【讨论】:

            猜你喜欢
            • 2013-10-29
            • 1970-01-01
            • 2013-10-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-21
            • 2019-06-19
            • 2011-03-20
            相关资源
            最近更新 更多