Converting std::string to char* to LPTSTR

Started by
7 comments, last by scorpion007 16 years, 5 months ago
I'm having trouble on converting std::string to a char*...it always say cannot convert...I tried to use the = operator and strcpy... But is there a way to convert the string to LPTSTR immediately...I need it for my output in a function I made that needs a LPTSTR output with a string input. I'm trying to convert it to char* but still cannot convert.
Advertisement
string::c_str
when I used .c_str() to the string it came out as "cannot convert from 'const char *' to 'LPTSTR'"
In that case you're obviously programming with UNICODE defined to true.
For VS2005 go to "Configuration Properties -> General -> Character Set" and set it to "Use Multi-Byte Character Set"
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
LPTSTR is typedefed as a non-const char*. You can't convert a std::string to a non-const buffer, you'll have to do something like:
char szBuff[256];Func(szBuff);std::string str = szBuff;
It may also be a unicode thing, as iMalc said.

Can we see some code to see exactly what you're doing?
LPTSTR is actually a generic text string type. It may or may not be "a non-const char*" as you say.

From MSDN, it's "An LPWSTR if UNICODE is defined, an LPSTR otherwise."
Quote:Original post by scorpion007
LPTSTR is actually a generic text string type. It may or may not be "a non-const char*" as you say.

From MSDN, it's "An LPWSTR if UNICODE is defined, an LPSTR otherwise."


From winnt.h:
#ifdef UNICODEtypedef LPWSTR PTSTR, LPTSTR;#elsetypedef LPSTR PTSTR, LPTSTR;#endiftypedef __nullterminated CHAR *NPSTR, *LPSTR, *PSTR;typedef __nullterminated WCHAR *NWPSTR, *LPWSTR, *PWSTR;

Meaning a LPTSTR is a non-const multi-byte or wide character string. My point is that it's always non-const, meaning you can't convert a std::string or std::wstring to it directly.
If you want to convert a narrow character string to a wide character string, you can use mbstowcs(), or if you're feeling adventurous, the widen() member function of the ctype facet of a std::locale. Alternately, if you're willing to use ATL, you can use the CA2T macro to create a TCHAR buffer from a const char *. Ex:
CA2T buffer(my_string.c_str());

This uses the default buffer size of 128, though. If you need a larger buffer, you should use the CA2TEX macro instead, which allows you to explicitly specify a buffer size.
Quote:Original post by Evil Steve
Meaning a LPTSTR is a non-const multi-byte or wide character string. My point is that it's always non-const, meaning you can't convert a std::string or std::wstring to it directly.


It's a *single*-byte (narrow) or wide character string, depending on UNICODE, as I already said.

This topic is closed to new replies.

Advertisement