1
#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;
}

Help needed on how to use strcasecmp, when i tried to compile, the compiler keep shows an error message

error: cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int strcasecmp(const char*, const char*)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Justpee
  • 181
  • 1
  • 3
  • 11

5 Answers5

4

strcasecmp takes a const char*, not a std::string as argument. Use strcasecmp(s.c_str(), "TEST") instead, or have a s be a C-style string in the first place.

Ben Steffan
  • 1,095
  • 12
  • 16
3

It means strcasecmp expect a C style string (0 terminated char[]) not a C++ string. You can get one with s.c_str().

kmkaplan
  • 18,655
  • 4
  • 51
  • 65
3

The strcasecmp() function expects a pointer to a null-terminated char string, you cannot pass a std::string directly to it.

The correct way to use this should be:

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

Moreover, the code looks incorrect in your program, because strcasecmp() returns a ZERO in case the strings are equal. So, you should be using the following:

if(strcasecmp(s, "TEST") == 0)
    cout << "equals"<< endl;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
The Apache
  • 1,076
  • 11
  • 28
1

you can try

strcasecmp(s.c_str(), "TEST")
tkrishtop
  • 734
  • 1
  • 8
  • 18
0

The strcasecmp() function is not specified in the C International standard. However, strcasecmp() is part of the POSIX.1-2001 and 4.4BSD specifications.

Under Cygwin you even need the additional line

#include <strings.h>

to make this function available in your own code.

To keep your code portable, I would forgo this function and rebuild its functionality myself:

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));
}
Markus Gans
  • 66
  • 1
  • 6