4

I have already tried strcmp and lstrcmp. I even tried to get do it with strlen but didn't work either, here is what I have

void check(LPCSTR lpText)
{
    if( strmp(lpText, "test") == 0)
    {
        MessageBoxW(0, L"equal", 0, 0); 
    }
    else
    {
        MessageBoxW(0, L"not equal", 0, 0); 
    }
}

It always returns 1 no matter what, also charset in settings is set to Use Multi-Byte Character Set if it matters.

method
  • 1,369
  • 3
  • 16
  • 29

2 Answers2

6

Try comparing it to a wide string literal if you're using wide strings:

if (lstrcmp(lpText, L"test") == 0) {
    // stuff
}

Edit: it seems that you were using the wrong character encoding.

  • 1
    It gives me this error: 'lstrcmpA' : cannot convert parameter 2 from 'const wchar_t [6]' to 'LPCSTR' – method Nov 21 '12 at 19:35
  • @Furious: *don't* explicitly call the `*W` functions. Here you can also see why. Had you used `MessageBox` instead of `MessageBoxW` and defined `_UNICODE` globally in the preprocessor it would work out of the box as suggested by H2CO3! `lstrcmpW` of course also does the job when compiled without `_UNICODE`. – 0xC0000022L Nov 21 '12 at 19:39
  • lpText declared LPCSTR. It's in the parameter list. – Benjamin Lindley Nov 21 '12 at 19:43
  • Sorry for the confusion guyz, my bad. Changed from MB to Unicode and now works. – method Nov 21 '12 at 19:54
  • @Furious, Multibyte is obsolete - don't use it unless you're dealing with an old codebase that's impossible to convert. – Mark Ransom Nov 21 '12 at 20:09
0

Old question, but for some learners like me.

If you use unicode setting, then LPCTSTR (here, 'T' means it varies according to UNICODE is defined or not) is const wchar_t *, so wcscmp can be used for comparing two LPCTSTR.

int wcscmp(
   const wchar_t *string1,
   const wchar_t *string2
);

E.g.,

// myStr is LPCTSTR
if (wcscmp(myStr, _T("mytext")) == 0) { // _T makes this to L"mytext" (if unicode).
  // myStr == "mytext"
}

(FYI, if not unicode, LPCTSTR is const char*)

Or, if you use CString(MFC project), then just == would work, which is equivalent to CStringT::Compare. It would automatically notice you're using UNICODE or not.

References(MSDN): 1 2 3

starriet
  • 2,565
  • 22
  • 23