当前位置:  开发笔记 > 编程语言 > 正文

将lptstr转换为char*

如何解决《将lptstr转换为char*》经验,为你挑选了3个好方法。

有人会碰巧知道如何将类型转换LPTSTRchar *C++吗?



1> JamesSugrue..:

取决于它是否是Unicode,它出现.如果不是Unicode,LPTSTR是char*,如果不是,则为w_char*.

在这里讨论得更好(接受的答案值得一读)



2> 小智..:

这有很多方法可以做到这一点.MFC或ATL的CString,ATL宏或Win32 API.

LPTSTR szString = _T("Testing");
char* pBuffer;

您可以使用ATL宏进行转换:

USES_CONVERSION;
pBuffer = T2A(szString);

CString的:

CStringA cstrText(szString);

或在Win32 API WideCharToMultiByte如果UNICODE被定义.



3> vahapt..:

如果编译器字符设置设置为Unicode字符集,则LPTSTR将被解释为wchar_t*.在这种情况下,需要Unicode到多字节字符转换.
(在Visual Studio中,设置位于项目属性\配置属性\常规\字符集)

下面的示例代码应该提供一个想法:

#include 

/* 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转换的另一个讨论:如何正确使用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

推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有