C ++: assign string L "" WCHAR []?

I have a WCHAR []:

WCHAR foo[200]; 

I want to copy the values โ€‹โ€‹into it:

 if (condition) { foo = L"bar"; } else { foo = L"odp"; } 

What is the best way to do this?

+4
source share
5 answers

Depending on what you need to do, you can change the type of foo:

 const WCHAR *foo; if (condition) { foo = L"bar"; } else { foo = L"odp"; } 

This is great if you don't need to add extra data to foo.

+1
source

wcscpy , although it would be best to use std::wstring .

 std::wstring foo; if (condition) foo = L"bar"; else foo = L"odp"; 

Or if you insist on using wcscpy :

 WCHAR foo[200]; if (condition) wcscpy(foo, L"bar"); else wcscpy(foo, L"odp"); 
+7
source

I would use std::wstring instead of a WCHAR array.

 std::wstring foo; ... if (condition) { foo = L"bar"; } else { foo = L"odp"; } 

An alternative would be to use some dirty wstrcpy functions coming from the C world, which is not approriate or safe if you can go in a cleaner C ++ way.

+1
source

If you are talking about assigning a value, then how you do it is perfect. If you use Visual C ++ and want to copy w-strings, use the more secure wcscpy_s function (it is more secure than wcscpy).

 errno_t wcscpy_s( wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource ); 

I will give you a small example:

 wchar* wstrOther = "hello"; wcscpy_s(foo, 200, wstrOther); 
+1
source

The variable foo is actually a pointer to the first line of the char line. Therefore, assigning another line to it will simply replace the pointer and memory leak.

The easiest way to do this is to use a string class like std::wstring , or use some old C functions like strncpy .

Using srd :: wstring will look like this:

 std::wstring foo; if(condition) { foo = L"bar"; } else { foo = L"odp"; } 
+1
source

Source: https://habr.com/ru/post/1312374/


All Articles