How to declare wchar_t and set its string value later on?

user780756 picture user780756 · Sep 28, 2013 · Viewed 30.1k times · Source

I am developing for Windows, I have not found adequate information on how to correctly declare and later on set a unicode string. So far,

wchar_t myString[1024] = L"My Test Unicode String!";

What I assume the above does is [1024] is the allocated string length of how many characters I need to have max in that string. L"" makes sure the string in quotes is unicode (An alt I found is _T()). Now later on in my program when I am trying to set that string to another value by,

myString = L"Another text";

I get compiler errors, what am I doing wrong?

Also if anyone has an easy and in-depth unicode app resource I'd like to have some links, used to have bookmarked a website which was dedicated to that but seems that now is gone.

EDIT

I provide the entire code, I intend to use this as a DLL function but nothing so far is returned.

#include "dll.h"
#include <windows.h>
#include <string>
#include <cwchar>

export LPCSTR ex_test()
{
wchar_t myUString[1024];
std::wcsncpy(myUString, L"Another text", 1024);

int myUStringLength = lstrlenW(myUString);

MessageBoxW(NULL, (LPCWSTR)myUString, L"Test", MB_OK);

int bufferLength = WideCharToMultiByte(CP_UTF8, 0, myUString, myUStringLength, NULL, 0, NULL, NULL);
if (bufferLength <= 0) { return NULL; } //ERROR in WideCharToMultiByte
return NULL;

char *buffer = new char[bufferLength+1];
bufferLength = WideCharToMultiByte(CP_UTF8, 0, myUString, myUStringLength, buffer, bufferLength, NULL, NULL);
if (bufferLength <= 0) { delete[] buffer; return NULL; } //ERROR in WideCharToMultiByte

buffer[bufferLength] = 0;

return buffer;
}

Answer

Dietmar K&#252;hl picture Dietmar Kühl · Sep 28, 2013

The easiest approach is to declare the string differently in the first place:

std::wstring myString;
myString = L"Another text";

If you insist in using arrays of wchar_t directly, you'd use wcscpy() or better wcsncpy() from <cwchar>:

wchar_t myString[1024];
std::wcsncpy(myString, L"Another text", 1024);