[英]How to convert std::wstring to a TCHAR*?
How to convert a std::wstring
to a TCHAR*
?如何将
std::wstring
转换为TCHAR*
? std::wstring.c_str()
does not work since it returns a wchar_t*
. std::wstring.c_str()
不起作用,因为它返回wchar_t*
。
How do I get from wchar_t*
to TCHAR*
, or from std::wstring
to TCHAR*
?我如何从
wchar_t*
到TCHAR*
,或从std::wstring
到TCHAR*
?
use this :用这个 :
wstring str1(L"Hello world");
TCHAR * v1 = (wchar_t *)str1.c_str();
#include <atlconv.h>
TCHAR *dst = W2T(src.c_str());
Will do the right thing in ANSI or Unicode builds.将在 ANSI 或 Unicode 构建中做正确的事情。
TCHAR* is defined to be wchar_t* if UNICODE is defined, otherwise it's char*.如果定义了 UNICODE,则 TCHAR* 定义为 wchar_t*,否则为 char*。 So your code might look something like this:
所以你的代码可能看起来像这样:
wchar_t* src;
TCHAR* result;
#ifdef UNICODE
result = src;
#else
//I think W2A is defined in atlbase.h, and it returns a stack-allocated var.
//If that's not OK, look at the documenation for wcstombs.
result = W2A(src);
#endif
in general this is not possible since wchar_t may not be the same size as TCHAR.通常这是不可能的,因为 wchar_t 可能与 TCHAR 的大小不同。
several solutions are already listed for converting between character sets.已经列出了几种用于在字符集之间转换的解决方案。 these can work if the character sets overlap for the range being converted.
如果字符集与正在转换的范围重叠,这些可以工作。
I prefer to sidestep the issue entirely wherever possible and use a standard string that is defined on the TCHAR character set as follows:我更喜欢尽可能完全回避这个问题,并使用在 TCHAR 字符集上定义的标准字符串,如下所示:
typedef std::basic_string<TCHAR> tstring;
using this you now have a standard library compatible string that is also compatible with the windows TCHAR macro.使用它,您现在拥有一个与 windows TCHAR 宏兼容的标准库兼容字符串。
You can use:您可以使用:
wstring ws = L"Testing123";
string s(ws.begin(), ws.end());
// s.c_str() is what you're after
Assuming that you are operating on Windows.假设您在 Windows 上操作。
If you are in Unicode build configuration, then TCHAR
and wchar_t
are the same thing.如果您使用 Unicode 构建配置,那么
TCHAR
和wchar_t
是一回事。 You might need a cast depending on whether you have /Z set for wchar_t
is a type versus wchar_t is a typedef.您可能需要转换,具体取决于您是否为
wchar_t
设置了 /Z 类型,而 wchar_t 是类型定义。
If you are in a multibyte build configuration, you need MultiByteToWideChar
(and vica versa).如果您处于多字节构建配置中,则需要
MultiByteToWideChar
(反之亦然)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.