user3400351
user3400351

Reputation: 233

How to convert std::wstring to a const TCHAR*?

I have the following wstring:

std::wstring testVal("Test");

Which I need to place inside this value:

 static const TCHAR* s_test_val;

So far I have tried:

 static const TCHAR* s_test_val = (const wchar_t*) testVal.c_str();
 static const TCHAR* s_test_val = (wchar_t*) testVal.c_str();
 static const TCHAR* s_test_val = (TCHAR*) testVal.c_str();
 static const TCHAR* s_test_val = (TCHAR*) testVal;

But without success; s_test_val keeps appearing as an empty string.

Upvotes: 0

Views: 331

Answers (2)

eerorika
eerorika

Reputation: 238441

static const TCHAR* s_test_val = testVal.c_str();

This one is correct on the condition that UNICODE is defined in which case TCHAR will be an alias of wchar_t.

If UNICODE isn't defined, then you would need to perform some conversion, but it might not be worth the effort to support non-unicode builds. Your attempt that uses a cast would silently do the wrong thing in that case while this one safely produces an error.

In case you don't care about non-unicode support (and I cannot think of a reason why anyone would), then I recommend minimising the use of TCHAR entirely.

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

Don't use TCHAR unless Windows 9x support is essential. Additionally, your static pointer pointing to an automatic variable is very suspicious. You either want:

static wchar_t constexpr const*  s_test_val = L"Test";

or

std::wstring testVal = L"Test";
wchar_t const* s_test_val = testVal.c_str();

or

std::wstring testVal = L"Test";
auto const s_test_val = testVal.c_str();

Upvotes: 0

Related Questions