Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting TCHAR to string in C++

Tags:

I'm trying to convert a TCHAR to a string as in:

std::string mypath; TCHAR path[MAX_PATH]; GetModuleFileName( NULL, path, MAX_PATH ); 

I need to set mypath to that of path. I did a simple loop and concatenated path[index] to mypath and this works but I don't like this way.

I'm new to C++ but have done plenty of C#. I've seen examples of the GetModuleFileName that passes in a "char" but it doesn't like it. It needs the TCHAR or a LPWSTR.

like image 313
David Avatar asked May 15 '11 03:05

David


People also ask

How to convert TCHAR to string?

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".

What is a TCHAR?

For Unicode platforms, TCHAR is defined as synonymous with the WCHAR type. MAPI clients can use the TCHAR data type to represent a string of either the WCHAR or char type. Be sure to define the symbolic constant UNICODE and limit the platform when it is required.

How do you find the length of a Tchar array?

Use _tcslen to find the length of a null-terminated array of TCHAR , if this is really what you wish to do. However, you might be better served by: Not using TCHAR at all an instead use only UTF-16 encoded text, the platform native encoding. Not using C strings and instead use std::wstring .


2 Answers

TCHAR is a macro defined as a char or wchar depending on what you have your character set defined to. The default after 2008 is have the character set to unicode. this code works if you change your character set.

int _tmain(int argc, _TCHAR* argv[]) {     TCHAR* bob ="hi";     string s = bob;     } 

Right click on the project settings and chage the folowing

enter image description here

if You want to use TCHAR as a Unicode character set use wstring

like image 75
rerun Avatar answered Sep 20 '22 06:09

rerun


When I really need to do it I use the following:

TCHAR  infoBuf[32767]; GetWindowsDirectory(infoBuf, 32767); 

And then I convert it to a wstring which can be converted to a standard std::string:

wstring test(&infoBuf[0]); //convert to wstring string test2(test.begin(), test.end()); //and convert to string. 
like image 40
OhadM Avatar answered Sep 19 '22 06:09

OhadM