C++ 将 lptstr 转换为 char*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/342772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert lptstr to char*
提问by user37875
Would anyone happen to know how to convert type LPTSTR
to char *
in C++?
有人会碰巧知道如何将类型转换LPTSTR
为char *
C++ 吗?
采纳答案by JamesSugrue
Depends if it is Unicode or not it appears. LPTSTR is char* if not Unicode, or w_char* if so.
取决于它是否是 Unicode 出现。如果不是 Unicode,则 LPTSTR 是 char*,如果是,则是 w_char*。
Discussed better here(accepted answer worth reading)
在这里讨论得更好(接受的答案值得一读)
回答by John Z
Here are a lot of ways to do this. MFC or ATL's CString, ATL macros, or Win32 API.
这里有很多方法可以做到这一点。MFC 或 ATL 的 CString、ATL 宏或 Win32 API。
LPTSTR szString = _T("Testing");
char* pBuffer;
You can use ATL macros to convert:
您可以使用 ATL 宏来转换:
USES_CONVERSION;
pBuffer = T2A(szString);
CString:
字符串:
CStringA cstrText(szString);
or the Win32 API WideCharToMultiByte
if UNICODE
is defined.
或 Win32 API(WideCharToMultiByte
如果UNICODE
已定义)。
回答by vahapt
If your compiler Character Setting is set to Unicode Character Set, then LPTSTRwill be interpreted as wchar_t*. In that case Unicode to Multibyte character conversion is required.
(In Visual Studio, setting is located at Project Properties\Configuration Properties\General\Character Set)
如果您的编译器 Character Setting 设置为Unicode Character Set,那么LPTSTR将被解释为wchar_t*。在这种情况下,需要将 Unicode 转换为多字节字符。
(在 Visual Studio 中,设置位于 Project Properties\Configuration Properties\General\Character Set)
The sample code below should give an idea:
下面的示例代码应该给出一个想法:
#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;
}
On the other hand, if your compiler Character Setting is set to Multibyte, then LPTSTRwill be interpreted as char*.
另一方面,如果您的编译器字符设置设置为多字节,则LPTSTR将被解释为char*。
In that case:
在这种情况下:
LPTSTR x = "test";
char* y;
y = x;
Also see:
另见:
Another discussion about wchar_t conversion: How do you properly use WideCharToMultiByte
MSDN Article: http://msdn.microsoft.com/en-us/library/dd374130(v=vs.85).aspx
Valid Code Page Identifiers: http://msdn.microsoft.com/en-us/library/dd317756(v=vs.85).aspx
关于 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
回答by Mark Ransom
char * pCopy = NULL;
if (sizeof(TCHAR) == sizeof(char))
{
size_t size = strlen(pOriginal);
pCopy = new char[size + 1];
strcpy(pCopy, pOriginal);
}
else
{
size_t size = wcstombs(NULL, pOriginal, 0);
pCopy = new char[size + 1];
wcstombs(pCopy, pOriginal, size + 1);
}
回答by maxtuzz
OK, so lets say that you HAVE to use Unicode. And you use some functions like LookupAccountSid, that are required for your program to function - but they return LPTSTR for important information you NEED to process as a string (for whatever reason - it's programming, stuff like this happens)
好的,让我们说您必须使用 Unicode。并且您使用了一些函数,例如 LookupAccountSid,这是您的程序运行所必需的 - 但它们返回 LPTSTR 以获得您需要作为字符串处理的重要信息(无论出于何种原因 - 它是编程,这样的事情会发生)
Now, if you were using multibyte - this wouldn't be an issue. But there is a way to solve it. This is my method and is admittedly sloppy. But nonetheless you should be able to see how it works.
现在,如果您使用多字节 - 这将不是问题。但是有一种方法可以解决它。这是我的方法,无可否认是草率的。尽管如此,您应该能够看到它是如何工作的。
const std::wstring &wstring = AcctName; // AcctName being my LPTSTR string
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, & wstring[0], (int)wstring[0], &strTo[0], size_needed, NULL, NULL);
char* charUserName = new char[strTo.size() + 1];
// Set charUserName via copying
std::copy(strTo.begin(), strTo.end(), charUserName);
charUserName[strTo.size()] = '#include <cstring>
#include <algorithm>
#include <tchar.h>
void lptstr2str(LPTSTR tch, char* &pch) // or (TCHAR* tch, char* &pch)
{
#ifndef UNICODE
std::memcpy(pch, tch, strlen(tch) + 1);
#else
size_t n =
sizeof(TCHAR) / sizeof(char)* wcsnlen(tch, std::string::npos);
pch = new char[n + 1];
std::memcpy(pch, tch, n + 1);
int len = n - std::count(pch, pch + n, NULL);
std::remove(pch, pch + n, NULL);
pch[len] = NULL;
#endif
}
';
SetUPI(charUserName); // charUserName being my converted char * -
// You don't need this last part - but this is an example of passing to method
// that takes a string
Any questions just ask. I realise this is an old post - but I like to post for people in the furture that come looking. (people like me)
有什么问题就问吧。我意识到这是一个旧帖子 - 但我喜欢为未来的人发帖。(像我这样的人)
回答by polfosol ?_?
I hope this helps someone, because it took me a while to figure out how to do it.
我希望这对某人有所帮助,因为我花了一段时间才弄清楚如何去做。
First of all, LPTSTR
is of pointer type and it is basically equivalent to TCHAR*
(assuming that <tchar.h>
is included).
Note that the size of TCHAR
varies based of the character encoding type. i.e. if unicode is defined, TCHAR
is equal to wchar_t
, otherwise it is char
.
首先,LPTSTR
是指针类型,它基本上等价于TCHAR*
(假设<tchar.h>
包含)。请注意, 的大小TCHAR
因字符编码类型而异。即,如果定义了 unicode,TCHAR
则等于wchar_t
,否则为char
。
Naturally, if you convert a wide character to a normal char
, you can only keep the LSB and may lose some data. This was somehow irritating for me. so I wrote the following code. Its main advantage is doing the conversion without losing any data.
当然,如果将宽字符转换为普通字符char
,则只能保留 LSB,可能会丢失一些数据。这让我有些恼火。所以我写了下面的代码。它的主要优点是在不丢失任何数据的情况下进行转换。
By the way, if you are okay with data loss, then wcstombs
does the job.
顺便说一句,如果您对数据丢失wcstombs
没有意见,那么就可以了。
LPCTSTR myLPCTSTR = getLPCTSTR();
TCHAR myT[500];
wcscpy(myT,myLPCTSTR);
char myC[500];
sprintf(myC, "%S", myT);
回答by Racky
I was missing some simple example so here it is:
我错过了一些简单的例子,所以这里是:
(for me char* is identical to char[])
(对我来说 char* 与 char[] 相同)
string mfc_to_zstring (CString &sref)
{
char nojoy[65536];
char *ptr, *psin = NULL;
string sot;
LPCTSTR p = sref;
#if UNICODE
if (sizeof(TCHAR) != sizeof(char))
{
size_t n = wcstombs(NULL, p, 0);
if (n > 65530)
{
psin = new char[n + 1];
wcstombs(psin, p, n + 1);
ptr = psin;
}
else
{
wcstombs(nojoy, p, n + 1);
ptr = nojoy;
}
sot = ptr;
if (psin != NULL)
delete psin;
}
else
{ std::cerr << "Aaargh! Microsoft horror.\n"; exit(1); }
#else
if (sizeof(TCHAR) == sizeof(char))
{
const char *ptr = p;
sot = ptr;
}
else
{ std::cerr << "Aaargh! You should never see this line\n"; exit(1); }
#endif
return sot;
}
回答by gorth
no doubt many (eg, us unix folk) will recoil in horror at the mad-hatter Microserf doublespeak - "if your compiler is in Unicode mode, use LPWSTR or stick a "T_" in front of it, but only if it's a static string, which is the same as an "L", or use T2A() if using ATL, but that's now outdated, or use VARIANT but not if linking with COM/OLE"...).
毫无疑问,许多人(例如,我们 unix 的人)会害怕发疯的 Microserf doublespeak - “如果您的编译器处于 Unicode 模式,请使用 LPWSTR 或在它前面贴上一个“T_”,但前提是它是静态的字符串,它与“L”相同,或者如果使用 ATL,则使用 T2A(),但现在已经过时,或者使用 VARIANT 但如果与 COM/OLE 链接则不使用“...)。
The "if (sizeof(TCHAR) == sizeof(char))" listed on this page is a logical attempt at a nice solution, but it won't compile - either the if-true won't compile or if-false wont' compile, depending on your compiler flags (Aaargh!). For a write-and-forget portable solution you'll need to resort to the [too-generic named] UNICODE macro. I offer this adaptation of the previous code:
此页面上列出的“if (sizeof(TCHAR) == sizeof(char))”是一个不错的解决方案的合乎逻辑的尝试,但它不会编译 - if-true 不会编译或 if-false 不会' 编译,取决于您的编译器标志(啊啊!)。对于写完即忘的便携式解决方案,您需要求助于 [过于通用的命名] UNICODE 宏。我提供了对以前代码的这种改编:
##代码##