Converting Code pages in c++

╄→尐↘猪︶ㄣ 提交于 2019-12-13 09:09:38

问题


What is equivalent of the C# string conversion code (between code pages):

public static string Convert(string s)
{
    Encoding encoder = Encoding.GetEncoding(858);
    return Encoding.Default.GetString(encoder.GetBytes(s));
}

in VC++ (not CLR), e.g. using WideCharToMultiByte/MultiByteToWideChar WinAPI functions?


回答1:


Yes, MultiByteToWideChar() and WideCharToMultiByte() are the equivalent Win32 functions, for example:

std::wstring Convert(const std::wstring &s)
{
    if (s.empty())
        return std::wstring();

    int len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), NULL, 0, NULL, NULL);
    if (len == 0)
        throw std::runtime_error("WideCharToMultiByte() failed"); 

    std::vector<char> bytes(len);

    len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), &bytes[0], len, NULL, NULL);
    if (len == 0)
        throw std::runtime_error("WideCharToMultiByte() failed"); 

    len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), NULL, 0);
    if (len == 0)
        throw std::runtime_error("MultiByteToWideChar() failed"); 

    std::wstring result;
    result.resize(len);

    len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), &result[0], len);
    if (len == 0)
        throw std::runtime_error("MultiByteToWideChar() failed"); 

    return result;
}


来源:https://stackoverflow.com/questions/25274797/converting-code-pages-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!