Sign in to follow this  
Revin122

Converting std::string to char* to LPTSTR

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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"

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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 UNICODE
typedef LPWSTR PTSTR, LPTSTR;
#else
typedef LPSTR PTSTR, LPTSTR;
#endif

typedef __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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this