Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string to LPCTSTR

New version of the typical question of how to convert from std::string to LPCTSTR.

Reading from different SO posts I learnt that I should do this:

CreateDirectory(path.c_str(),NULL);

And still the compiler gives error because cannot convert from const char * to LPCTSTR.

I tried:

CreateDirectory((LPCTSTR)path.c_str(),NULL);

No errors!

Still the directory created (in the correct place) is called:

D:\\something\\㩄ぜ弲久䅓余屓䱆彄湡敤屲䵉ⴱ㠶ⴰⵃㅇ㉜洰⵭就䥄牃獥汵獴촀췍췍췍췍췍췍췍﷍﷽꯽ꮫꮫꮫﺫﻮﻮ

which is not exactly what I wanted, as you can guess...

So what am I missing? Is it something related with UNICODE/ANSI? How can I resolve this?

like image 416
Ander Biguri Avatar asked May 23 '13 10:05

Ander Biguri


People also ask

How do you convert STD string to CString?

Converting a std::string to a CString is as simple as: std::string stdstr("foo"); CString cstr(stdstr. c_str()); This works for both UNICODE and MBCS projects.

What is Lpctstr?

LPCTSTR is a pointer to a const TCHAR string, ( TCHAR being either a wide char or char depending on whether UNICODE is defined in your project) LPTSTR is a pointer to a (non-const) TCHAR string.

How do you convert Wstring to Lpcwstr?

This LPCWSTR is Microsoft defined. So to use them we have to include Windows. h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.

How do you convert Lpcstr to CString?

LPCTSTR szTmp = _T("My String"); CString cszMyString(szTmp); // one way. CString cszMyString = szTmp; // another way. Rama Krishna's asnwer will help you.


2 Answers

Try to look at this page: What-are-TCHAR-WCHAR-LPSTR-LPWSTR-LPCTSTR-etc. If you are using MSVC, than you may have set Unicode for project and LPCSTR is "translated" to const wchar_t *, which is not compatible with const char *

By doing this: (LPCTSTR)path.c_str() you are taking two chars from original string and create from them one unicode wchar_t letter. Thats way you are getting "chinese" characters.

like image 113
Martin Perry Avatar answered Sep 20 '22 13:09

Martin Perry


Your problem here is the fact that LPCTSTR is resolved to wchar_t* or char* based on whether your build supports unicode (unicode flag set or not).

To explicitly call the char* version, call CreateDirectoryA().

like image 26
Mario Avatar answered Sep 22 '22 13:09

Mario