method
method

Reputation: 1389

How to compare LPCSTR

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.

Upvotes: 4

Views: 8196

Answers (2)

starriet 차주녕
starriet 차주녕

Reputation: 3958

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

Upvotes: 0

user529758
user529758

Reputation:

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.

Upvotes: 6

Related Questions