Namodaya Balaarachchi
Namodaya Balaarachchi

Reputation: 371

Assign variable wstring to Char array in C++

I have char array as follows:

TCHAR name[256] = L"abc";

Also I have another wstring vector as follows,

std::vector<std::wstring> nameList;
nameList.push_back(L"cde");
nameList.push_back(L"fgh");

I want to assign nameList vector first element to name array,

Can any one help for that me?

Upvotes: 0

Views: 827

Answers (2)

Steven W. Klassen
Steven W. Klassen

Reputation: 1571

Given your question and the assumption that you must use an array instead of a wstring, your best bet may be to use either std::copy or even an old fashioned memcpy. However these are dangerous for the following two reasons:

  1. If TCHAR is not actually a wchar_t there are likely be to memory errors.
  2. If nameList contains a string that is longer than 255 TCHAR characters you will have a buffer overflow.

That said, you can do this safely with the following:

if (nameList[0].size() >= 256) {
    throw std::length_error("string too long");
}
std::copy(nameList[0].begin(), nameList[0].end(), name);
name[nameList[0].size()] = TCHAR(0);

You could also add a static_assert to force a compiler error if TCHAR is not a wchar_t, but it probably isn't necessary as the copy would perform any implicit conversion on a character by character basis.

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

You can use std::copy; name is an array with a bound, but it's usage as a function argument decays to a pointer to it's first element, which satisfies the requirements for an output iterator.

So you can:

wchar_t name[256] = L"abc";

std::vector<std::wstring> nameList;
nameList.push_back(L"cde");
nameList.push_back(L"fgh");

std::copy(nameList.front().begin(), nameList.front().end(), name);

Note that: this will not add any trailing \0 terminator to the buffer; If you wanted to replace/overwrite name, you should as well just use std::wstring and save yourself some hassles

Upvotes: 2

Related Questions