![](/img/trans.png)
[英]cannot convert 'const char*' to 'LPCWSTR {aka const wchar_t*}'
[英]How convert LPCWSTR to wchar_t*?
我需要將LPCWSTR
數據轉換為wchar_t*
。 我嘗試了很多方法和一些工作,但是當我嘗試獲取它們的代碼頁時,它們顯示了不同的值。
代碼概述:
std::string ChineseCharacter(LPCWSTR Data) //Data value: "丂\n"
{
CString sHexValue = "";
std::wstring sData(Data);
wchar_t* str1 = (wchar_t*)Data;
//wchar_t* str2 = (wchar_t*)_wcsdup(sData.c_str());
wchar_t* str3 = (wchar_t*)(L"丂\n"); //u4E02 -- CP 8140 ** CP is needed
for (int i = 0; i < 4; i++)
{
sHexValue2.Format("%02x", str1[i]);//-- 4E02 -- FAIL
//sHexValue2.Format("%02x", str2[i]);//-- 4E02 -- FAIL
sHexValue2.Format("%02x", str3[i]);//-- First loop: 81, second one: 40 -- OK
}
}
根據觀察者的說法,這些值是:
str1= L"丂\n"
str3= L"@\n"
我的疑問是,如何將Data
的值傳遞給wchar_t*
,就像我對值進行硬編碼時一樣?
LPCWSTR
只是const wchar_t*
的別名。 要將其轉換為wchar_t*
,您可以使用const_cast
,例如:
wchar_t* str = const_cast<wchar_t*>(Data);
(只需確保您沒有向指向的 memory 寫入任何內容)。
但是,您顯示的代碼中沒有任何內容需要使用非常量wchar_t*
(或std::wstring
),因此您可以直接循環Data
,根本不需要將LPCWSTR
轉換為wchar_t*
,例如:
std::string ChineseCharacter(LPCWSTR Data)
{
CString sHexValue;
for (int i = 0; (i < 4) && (Data[i] != L'\0'); ++i)
{
sHexValue.Format("%02hx", static_cast<unsigned short>(Data[i]));
}
return static_cast<char*>(sHexValue);
}
或者,僅使用標准 C++:
std::string ChineseCharacter(const wchar_t *Data)
{
std::ostringstream sHexValue;
for (int i = 0; (i < 4) && (Data[i] != L'\0'); ++i)
{
sHexValue << std::setw(2) << std::setfill('0') << std::hex << static_cast<unsigned short>(Data[i]);
}
return sHexValue.str();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.