-3

I am writing a code for comparing two strings of type LPSTR and wchar_t type. The contents of strings are same but the output is showing that the strings are different. Below is screenshot of the complete code.

#include <iostream>
#include <string.h>
#include <wtypes.h>
using namespace std;
int main(int argc, char** argv) 
{
    LPSTR str1= "Abcdef123456";
    wchar_t *str2 = L"Abcdef123456";
    if(!strcmp((char *)str1, (char *)str2))
    {
        cout<<"same";   
    }
    else
    {
            cout<<"diff";
    }

    return 0;
}

Upon execution, the output is diff. I think the output should be same. Please help.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
akashagrawal
  • 3
  • 1
  • 7
  • Why do you think they should be the same? – DeiDei Mar 08 '17 at 14:14
  • 3
    Your call to`strcmp` is comparing single byte characters. The first string is composed of single byte characters, the second of wide 2-byte characters. They are not the same thing. You need to convert the strings to the same storage format before you do the comparison. – Baldrick Mar 08 '17 at 14:15
  • 2
    If `"A"` and `L"A"` had been the same, why would we need two versions? – Bo Persson Mar 08 '17 at 14:23
  • @DeiDei I thought that since the contents are same, the strings should be same. But now I know the difference between the two strorage types. – akashagrawal Mar 09 '17 at 05:40
  • Thanks @Baldrick for the clear explanation. – akashagrawal Mar 09 '17 at 05:41

1 Answers1

1

L'A' has a different representation in memory than 'A'. If you pretend that an array of wchar_t is an array of char (by explicit conversion char*) and compare it to another array of char with different representation, they will compare different.

The output is as expected.


A correct way to compare the strings is to convert the narrow string to a wide string. That isn't exactly trivial to do correctly, so here is an example:

auto length = std::strlen(str1);
std::wstring temp(length, L'\0');
std::mbstowcs(&temp[0], str1, length);
if (!wcscmp(temp.c_str(), str2))
   // ...
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thanks @user2079303 for the solution, this works for me. Please also explain me what `wstring temp(length, L'\0')` does here. – akashagrawal Mar 09 '17 at 05:32
  • @akashagrawal it constructs a wide string object for the buffer where the narrow string is converted into. – eerorika Mar 09 '17 at 08:14
  • Hey thank you so much @user2079303 . The code works but now the problem is that on debugging, hovering over `str2` shows the string value whereas hovering on `c_str()` does not show the value of string. Also, due to this, the conditional part is not working properly. Please help me with that. – akashagrawal Mar 09 '17 at 13:06
  • @akashagrawal I used wrong length originally. That should be fixed now. If you would like to see the content of a string object in a debugger, you should contact the sales team of your debugger provider. – eerorika Mar 10 '17 at 22:40