没有躲过的坑--wstring与string的转换

wstring 是指的宽字节。

typedef basic_string<char> string; 
typedef basic_string<wchar_t> wstring; 

在实际工程中,我们往往需要把string转换为wstring,你可以会进行百度或是Google,很轻松找到转换的方法。但是这里就隐含着巨大的坑儿。
看看这个转换吧:

std::wstring WStringToWString(const std::string& str) {
    int size_str = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
    wchar_t *wide = new wchar_t[size_str];
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, size_str);
    std::wstring return_wstring(wide);
    delete[] wide;
    wide = NULL;
    return return_wstring;
}

也许上面的代码帮你解决了问题,但是暂时的。当str = “我是中文”的时候,你会发现,无法完成正确的转换,导致乱码。

因此,为了增加你程序的健壮性,还是寻找另一种方法吧,如下:

std::wstring StringToWString(const std::string& str)
{
    setlocale(LC_ALL, "chs");
    const char* point_to_source = str.c_str();
    size_t new_size = str.size() + 1;
    wchar_t *point_to_destination = new wchar_t[new_size];
    wmemset(point_to_destination, 0, new_size);
    mbstowcs(point_to_destination, point_to_source, new_size);
    std::wstring result = point_to_destination;
    delete[]point_to_destination;
    setlocale(LC_ALL, "C");
    return result;
}

你可能感兴趣的:(String)