How to declare wchar_t and set its string value later?

I am developing for Windows, I did not find adequate information on how to declare correctly, and then set the Unicode string. For now

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

What I assume above is [1024] - this is the length of the highlighted line, how many characters I need to have on that line. L "" ensures that the quoted string is unicode (An alt I found _T ()). Now later in my program, when I try to set this line to a different value,

 myString = L"Another text"; 

I get compiler errors, what am I doing wrong?

Also, if someone has a simple and comprehensive Unicode application resource, I would like to have some links that used to be linked to a website that was dedicated to this, but it seems that now it is gone.

EDIT

I provide all the code, I intend to use it as a DLL function, but nothing 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; } 
+7
c ++ string unicode wchar
source share
2 answers

The easiest way is to declare a string in different ways:

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

If you insist on using wchar_t arrays directly, you should use wcscpy() or better wcsncpy() from <cwchar> :

 wchar_t myString[1024]; std::wcsncpy(myString, L"Another text", 1024); 
+5
source share
 wchar_t myString[1024] = L"My Test Unicode String!"; 

initializes an array e.g.

 wchar_t myString[1024] = { 'M', 'y', ' ', ..., 'n', 'g', '\0' }; 

but

 myString = L"Another text"; 

is an assignment that u cannot perform with arrays. u need to copy the contents of the new line into your old array:

 const auto& newstring = L"Another text"; std::copy(std::begin(newstring), std::end(newstring), myString); 

or if the pointer

 wchar_t* newstring = L"Another text"; std::copy(newstring, newstring + wsclen(newstring) + 1, myString); 

or like nawaz suggested using copy_n

 std::copy_n(newstring, wsclen(newstring) + 1, myString); 
+3
source share

All Articles