Reputation: 1471
I have been trying to convert a wstring to a char[] with no success so far. Are these to types totally incompatible or is there a way to convert from one to the other?
I've tried below two approaches with no luck so far.
char const testTwo[] = testOne;
char const testTwo[] = testOne.c_str();
Upvotes: 1
Views: 918
Reputation: 238281
First, you must find out how the std::wstring
is encoded. You should take a look at the documentation of the API where you get that string.
std::wstring
is typically encoded in system native wide encoding. What the native encoding is, should be specified in the documentation of the system that you are targeting. The native encoding is often be different across different systems, which needs to be taken care of if you intend to target multiple systems. The native wide encoding of Windows is UTF-16, while POSIX typically uses UTF-32.
Next you need to decide what encoding you intend to use for the array of narrow characters. The choice probably depends on what you intend to do with the narrow string. A typically common choice is either UTF-8 or the system native narrow encoding. Just like the wide encoding, the native narrow encoding is system specific. UTF-8 is fairly common on POSIX systems while Windows uses a constant width character set, which depends on the language of the system.
At this point, you should know what encoding you are converting from and to. If you're converting both from wide native encoding to narrow native encoding, then you're in luck. There is a standard function for this: std::wcsrtombs
.
If either of the encodings is not the native one, then you need to look up the documentation of the respective encodings for what each code unit, code point, grapheme etc. map to. Unicode specification can be found here. If you're converting into non-unicode, then you need to decide what to do with characters that don't have a corresponding code point in the target encoding.
As always, it is a good idea to save time by using existing software. You can skip learning different encodings and their conversions by using an existing library such as iconv.
P.S. You probably have no way of knowing the length of the resulting narrow string at compile time, so you probably need to allocate the array dynamically. This also means that the array cannot be const. I recommend using std::string
for this purpose
Upvotes: 2