char* to const wchar_t * conversion

2019-05-03 07:42发布

问题:

I need to convert character pointer to a w_char * in order to use ParseNetworkString(). I've tried finding solutions to this myself, and while I have found one solution, there is one issue which blocks me from using it:

b1naryatr0phy said in an other post:

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

this almost works for me, except that I can't just pass the string explicity, as its value is not always going to be the same, meaning I can't just put it in quotes. If I replace the parameter with a function call, then the first line gives me an error (example: std::wstring name(LgetIpAddress()); I've tried std::wstring name(L" " + getIpAddress() + " "); , thinking that it just needs a quotation mark after the L, but that doesn't work either.. any suggestions?

Thanks! :)

Extra Kudos to whoever can answer this!

link to other post: I want to convert std::string into a const wchar_t *

P.S. Sorry, just to clarify, getIpAddress returns a character pointer

回答1:

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;
}


回答2:

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.



回答3:

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.