【问题标题】:utf-8 to/from utf-16 problemutf-8 到/从 utf-16 问题
【发布时间】:2011-01-11 23:29:13
【问题描述】:

我基于这两个转换函数和 StackOverflow 上的答案,但是来回转换不起作用:

std::wstring    MultiByteToWideString(const char* szSrc)  
{
 unsigned int iSizeOfStr = MultiByteToWideChar(CP_ACP, 0, szSrc, -1, NULL, 0);  
 wchar_t* wszTgt = new wchar_t[iSizeOfStr];  
 if(!wszTgt)    assert(0);  
  MultiByteToWideChar(CP_ACP, 0, szSrc, -1, wszTgt, iSizeOfStr);  
 std::wstring wstr(wszTgt);  
delete(wszTgt);  
return(wstr);  
}

std::string WideStringToMultiByte(const wchar_t* wszSrc)  
{  
    int iSizeOfStr = WideCharToMultiByte(CP_ACP, 0, wszSrc, -1, NULL, 0, NULL, NULL);  
    char* szTgt = new char[iSizeOfStr];  
    if(!szTgt)  return(NULL);  
    WideCharToMultiByte(CP_ACP, 0, wszSrc, -1, szTgt, iSizeOfStr, NULL, NULL);  
    std::string str(szTgt);  
    delete(szTgt);  
    return(str);  
}  

[...]   

// はてなブ in utf-16
wchar_t wTestUTF16[] = L"\u306f\u3066\u306a\u30d6\u306f\u306f";

// shows the text correctly  
::MessageBoxW(NULL, wTestUTF16, L"Message", MB_OK);  

// convert to UTF8, and back to UTF-16  
std::string strUTF8 = WideStringToMultiByte(wTestUTF16);  
std::wstring wstrUTF16 = MultiByteToWideString(strUTF8.c_str());  

// this doesn't show the proper text.  Should be same as first message box  
::MessageBoxW(NULL, wstrUTF16.c_str(), L"Message", MB_OK);

【问题讨论】:

    标签: c++ unicode winapi utf-8 utf-16


    【解决方案1】:

    查看WideCharToMultiByte() 的文档。 CP_ACP 使用当前系统代码页进行转换。这是一个非常有损的。你想要 CP_UTF8。

    【讨论】:

    • 如果我将所有四个 CP_ACP 更改为 CP_UTF8 就可以正常工作...谢谢!
    • 仅当 char* 数据始终为 UTF-8 时才有效。如果您需要将数据与其他 Ansi 语言相互转换,那么您每次都必须使用正确的代码页。
    猜你喜欢
    • 2013-02-25
    • 2014-08-21
    • 2019-02-02
    • 2021-01-30
    • 2012-08-18
    • 2021-01-06
    • 1970-01-01
    • 2016-05-31
    • 2010-10-26
    相关资源
    最近更新 更多