char* to const wchar_t * conversion

空扰寡人 提交于 2019-12-05 09:39:38

What's the type of getIpAddress()?

Here's a snippet showing how to convert a string to a wstring (using standard C++11, no error checking):

wstring to_wstring(string const& str)
{
  size_t len = mbstowcs(nullptr, &str[0], 0);
  if (len == -1) // invalid source str, throw
  wstring wstr(len, 0);
  mbstowcs(&wstr[0], &str[0], wstr.size());
  return wstr;
}

You looked at only part of the other answer. It continues with explaining you need to do a MultiByteToWideChar to convert from an 8 bit string to a 16 bit one.

This assumes that wchar_t uses UTF-16 on your platform (which I presume is Windows, from your mention of ParseNetworkString()). It also assumes that the char* uses UTF-8 instead of a legacy encoding, since you really shouldn't be using legacy encodings anyway, even on Windows.

#include <codecvt>

int main() {
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> convert;

    std::wstring name = convert.from_bytes("Steve Nash");
    const wchar_t* szName = name.c_str();
}

If you are using legacy encodings then you should fix that, either by moving over to wchar_t APIs entirely (assuming you don't care about portable code) or by using UTF-8 as your internal char* encoding. If you insist on using legacy encodings then you'll need to use one of the functions that handles converting them, such as mbstowcs() (which is locale sensitive, which brings in a whole host of new problems), or use MultiByteToWideChar() which has some similar problems but meshes better with Windows locales.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!