Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to a TCHAR array

Tags:

c++

tchar

I have a TCHAR array in my C++ code which I want to assign static strings to it.

I set an initial string to it via

TCHAR myVariable[260] = TEXT("initial value");

Everything works fine on this. However, when I split it in two lines as in

TCHAR myVariable[260];
myVariable = TEXT("initial value");

it bugs and gives a compiler error:

error C2440: '=': cannot convert from 'const char [14]' to 'TCHAR [260]'

shouldn't the TEXT() function do exactly what I want here? convert the given string to TCHARs? Why does it work, when putting the two lines together? What do I have to change in order to get it working?

Some other confusing thing I have encountered:

I've searched the internet for it and have seen that there are also _T() and _TEXT() and __T() and __TEXT(). What are they for? Which of them should I use in what environment?

like image 382
Etan Avatar asked Oct 10 '09 12:10

Etan


People also ask

How do you define a Tchar?

The macro _UNICODE is defined when you set Character Set to "Use Unicode Character Set", and therefore TCHAR would mean wchar_t . When Character Set if set to "Use Multi-Byte Character Set", TCHAR would mean char .

How do you convert Wstring to Tchar?

So depending on your compilation configuration, you can convert TCHAR* to string or wstring. To use UNICODE character set, click Project->Properties->Configuration Properties->General->Character Set, and then select "Use Unicode Character Set".


1 Answers

The reason the assignment doesn't work has very little to do with TCHARs and _T. The following won't work either.

char var[260];
var = "str";   // fails

The reason is that in C and C++ you can't assign arrays directly. Instead, you have to copy the elements one by one (using, for example, strcpy, or in your case _tcscpy).

strcpy(var, "str");

Regarding the second part of your question, TEXT, _T and the others are macros, that in Unicode builds turn a string literal to a wide-string literal. In non-Unicode builds they do nothing.

like image 163
avakar Avatar answered Sep 17 '22 03:09

avakar