I have a WCHAR[]:
WCHAR foo[200];
I want to copy values into it:
if (condition)
{
foo = L"bar";
}
else
{
foo = L"odp";
}
What is the best way to do this?
I have a WCHAR[]:
WCHAR foo[200];
I want to copy values into it:
if (condition)
{
foo = L"bar";
}
else
{
foo = L"odp";
}
What is the best way to do this?
I would use std::wstring
instead of a WCHAR
array.
std::wstring foo;
...
if (condition)
{
foo = L"bar";
}
else
{
foo = L"odp";
}
The alternative would be to use some dirty wstrcpy functions coming from the C world, what is not approriate or safe if you can go the cleaner C++ way.
wcscpy
, although the superbest thing would be to use std::wstring
instead.
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");
If you are talking about assigning a value, the way you are doing it is perfect. If you are using Visual C++ and want to copy w-strings consider using the more secure function wcscpy_s (it is more secure than wcscpy).
errno_t wcscpy_s(
wchar_t *strDestination,
size_t numberOfElements,
const wchar_t *strSource
);
I'll give you a short example:
wchar* wstrOther = "hello";
wcscpy_s(foo, 200, wstrOther);
The foo
variable is actually a pointer to the first char of the string. So assigning another string to it will just replace the pointer and leak memory.
The simplest way to do this is using a string class, like std::wstring
, or using some old C functions like strncpy
.
Using srd::wstring it would look like:
std::wstring foo;
if(condition)
{
foo = L"bar";
}
else
{
foo = L"odp";
}
Depending on exactly what you need to do, you could change the type of foo:
const WCHAR *foo;
if (condition)
{
foo = L"bar";
}
else
{
foo = L"odp";
}
This is fine if don't need to append any more data to foo.