tags:

views:

81

answers:

5

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?

A: 

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.

jdehaan
+5  A: 

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");
avakar
+1  A: 

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);
Simon
A: 

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";
}
OrB
+1  A: 

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.

R Samuel Klatchko