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.
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))
// ...