XHLin XHLin - 4 months ago 26
C++ Question

How to compare a wstring with a _T("some String")?

I have a function

wstring A2T(const string& str)
to convert
string
to
wstring
. But I cannot get the correct value when I compare the return value with a
const wstring
. For example;

wstring strOn = A2T("on");
if ( strOn == _T("on"))
{
SetItemSwitch(true);
}
else
{
SetItemSwitch(false);
}


The
if(strOn == _T("on"))
statement is always false. What is wrong with my code?

This is the
A2T
:

std::wstring A2T(const string& str)
{
if (str.empty()) return std::wstring();
int sz = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);

std::wstring res(sz, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], -1, &res[0], sz);
return res;
}

Answer

The issue is in the interpretation (or use of) of the return from the first call to MultiByteToWideChar - it will return the size required including the terminating NULL character. When creating the wide string, the count for NULL should be removed from the size, the string will add that internally.

In addition, on the second call, use the actual sizes of the strings; this is to avoid the MultiByteToWideChar from processing the buffer including any terminating NULL characters (their presence is already catered for in the string size calculations). Again, the strings will manage the NULL internally.

std::wstring A2T(const std::string& str)
{
    if (str.empty())
        return std::wstring();
    int sz = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);

    std::wstring res(sz - 1, 0);
    //                  ^^^ count to "remove" the NULL
    MultiByteToWideChar(CP_UTF8, 0, &str[0], str.size(), &res[0], res.size());
    //                                       ^^^ use actual sizes
    return res;
}

Depending on the version of the compiler being used, you could also investigate the use of std::basic_string::data for res.data() over the use of &res[0].