utf8与utf16转换

1.UTF8与UTF16编码转换

std::string ConvertFromUtf16ToUtf8(const std::wstring& wstr)
{
    std::string convertedString;
    int requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0);
    if(requiredSize > 0)
    {
        std::vector<char> buffer(requiredSize);
        WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buffer[0], requiredSize, 0, 0);
        convertedString.assign(buffer.begin(), buffer.end() - 1);
    }
    return convertedString;
}
 
std::wstring ConvertFromUtf8ToUtf16(const std::string& str)
{
    std::wstring convertedString;
    int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);
    if(requiredSize > 0)
    {
        std::vector<wchar_t> buffer(requiredSize);
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &buffer[0], requiredSize);
        convertedString.assign(buffer.begin(), buffer.end() - 1);
    }
 
    return convertedString;
}

void SetWindowTextUtf8(HWND hWnd, const std::string& str)
{
    std::wstring wstr = ConvertUtf8ToUtf16(str);
    SetWindowTextW(hWnd, wstr.c_str());
}
 
std::string GetWindowTextUtf8(HWND hWnd)
{
    std::string str;
    int requiredSize = GetWindowTextLength(hWnd) + 1; //We have to take into account the final null character.
    if(requiredSize > 0)
    {
        std::vector<wchar_t> buffer(requiredSize);
        GetWindowTextW(hWnd, &buffer[0], requiredSize);
        std::wstring wstr(buffer.begin(), buffer.end() - 1);
        str = ConvertUtf16ToUtf8(wstr);
    }
    return str;
}

2.强制VisualStudio使用UTF-8编码

  • 方法1
    stdafx.h头文件中添加如下代码:
#pragma execution_character_set("utf-8")
  • 方法2
    在c/c++属性页的命令行添加/execution-charset:utf-8,如下图
    在这里插入图片描述

3.解决VisualStudio在调试窗口UTF8字符串显示乱码

参考http://www.nubaria.com/en/blog/?p=289

默认的, VC调试器只能正常显示ANSI字符串及UNICODE字符串, 而UTF-8字符串及其他格式则无法显示

这里无需编写插件及修改配置文件,只需要将要显示的字符串拉到Watch中,并在变量后面添加,s8即可显示

在这里插入图片描述–>在这里插入图片描述

同样类型的功能也应该很熟悉

,数字 将变量拆分为数组显示, 数字是要显示多少位, 此法对const char*这类原始字符串非常有用

,x 16进制查看
,hr 查看Windows HRESULT解释
,wm Windows消息,例如0x0010, wm 显示 WM_CLOSE

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章