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?
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.
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.
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.
LPCTSTR szTmp = _T("My String"); CString cszMyString(szTmp); // one way. CString cszMyString = szTmp; // another way. Rama Krishna's asnwer will help you.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With