[英]How to convert std::wstring to a TCHAR*?
如何將std::wstring
轉換為TCHAR*
? std::wstring.c_str()
不起作用,因為它返回wchar_t*
。
我如何從wchar_t*
到TCHAR*
,或從std::wstring
到TCHAR*
?
用這個 :
wstring str1(L"Hello world");
TCHAR * v1 = (wchar_t *)str1.c_str();
#include <atlconv.h>
TCHAR *dst = W2T(src.c_str());
將在 ANSI 或 Unicode 構建中做正確的事情。
如果定義了 UNICODE,則 TCHAR* 定義為 wchar_t*,否則為 char*。 所以你的代碼可能看起來像這樣:
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
通常這是不可能的,因為 wchar_t 可能與 TCHAR 的大小不同。
已經列出了幾種用於在字符集之間轉換的解決方案。 如果字符集與正在轉換的范圍重疊,這些可以工作。
我更喜歡盡可能完全回避這個問題,並使用在 TCHAR 字符集上定義的標准字符串,如下所示:
typedef std::basic_string<TCHAR> tstring;
使用它,您現在擁有一個與 windows TCHAR 宏兼容的標准庫兼容字符串。
您可以使用:
wstring ws = L"Testing123";
string s(ws.begin(), ws.end());
// s.c_str() is what you're after
假設您在 Windows 上操作。
如果您使用 Unicode 構建配置,那么TCHAR
和wchar_t
是一回事。 您可能需要轉換,具體取決於您是否為wchar_t
設置了 /Z 類型,而 wchar_t 是類型定義。
如果您處於多字節構建配置中,則需要MultiByteToWideChar
(反之亦然)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.