有人知道如何在C++中将类型LPTSTR转换为char *吗?
发布于 2008-12-05 03:03:08
取决于它是否显示为Unicode。如果不是Unicode,则LPTSTR为char*;如果是,则为w_char*。
Discussed better here (值得阅读的接受答案)
发布于 2008-12-05 03:02:57
这里有很多方法可以做到这一点。MFC或ATL的CString、ATL宏或Win32 API。
LPTSTR szString = _T("Testing");
char* pBuffer;可以使用ATL宏来转换:
USES_CONVERSION;
pBuffer = T2A(szString);CString:
CStringA cstrText(szString);或Win32接口WideCharToMultiByte (如果定义了UNICODE )。
发布于 2011-03-08 22:17:27
如果您的编译器字符设置设置为Unicode字符集,则LPTSTR将被解释为wchar_t*。在这种情况下,需要将Unicode字符转换为多字节字符。
(在Visual Studio中,设置位于项目属性\配置属性\常规\字符集)
下面的示例代码应该给出一个概念:
#include <windows.h>
/* string consisting of several Asian characters */
LPTSTR wcsString = L"\u9580\u961c\u9640\u963f\u963b\u9644";
//LPTSTR wcsString = L"OnlyAsciiCharacters";
char* encode(const wchar_t* wstr, unsigned int codePage)
{
int sizeNeeded = WideCharToMultiByte(codePage, 0, wstr, -1, NULL, 0, NULL, NULL);
char* encodedStr = new char[sizeNeeded];
WideCharToMultiByte(codePage, 0, wstr, -1, encodedStr, sizeNeeded, NULL, NULL);
return encodedStr;
}
wchar_t* decode(const char* encodedStr, unsigned int codePage)
{
int sizeNeeded = MultiByteToWideChar(codePage, 0, encodedStr, -1, NULL, 0);
wchar_t* decodedStr = new wchar_t[sizeNeeded ];
MultiByteToWideChar(codePage, 0, encodedStr, -1, decodedStr, sizeNeeded );
return decodedStr;
}
int main(int argc, char* argv[])
{
char* str = encode(wcsString, CP_UTF8); //UTF-8 encoding
wchar_t* wstr = decode(str, CP_UTF8);
//If the wcsString is UTF-8 encodable, then this comparison will result to true.
//(As i remember some of the Chinese dialects cannot be UTF-8 encoded
bool ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0;
delete str;
delete wstr;
str = encode(wcsString, 20127); //US-ASCII (7-bit) encoding
wstr = decode(str, 20127);
//If there were non-ascii characters existing on wcsString,
//we cannot return back, since some of the data is lost
ok = memcmp(wstr, wcsString, sizeof(wchar_t) * wcslen(wcsString)) == 0;
delete str;
delete wstr;
}另一方面,如果您的编译器字符设置设置为多字节,那么LPTSTR将被解释为char*。
在这种情况下:
LPTSTR x = "test";
char* y;
y = x;另请参阅:
关于wchar_t转换的另一个讨论:How do you properly use WideCharToMultiByte
MSDN文章:http://msdn.microsoft.com/en-us/library/dd374130(v=vs.85).aspx
有效代码页标识符:http://msdn.microsoft.com/en-us/library/dd317756(v=vs.85).aspx
https://stackoverflow.com/questions/342772
复制相似问题