在 C++ 中转换代码页 [英] Converting Code pages in c++

查看:45
本文介绍了在 C++ 中转换代码页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 字符串转换代码的等价物(代码页之间):

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));
}

在 VC++(不是 CLR)中,例如使用 WideCharToMultiByte/MultiByteToWideChar WinAPI 函数?

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

推荐答案

是的,MultiByteToWideChar()WideCharToMultiByte() 是等效的 Win32 函数,例如:

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;
}

这篇关于在 C++ 中转换代码页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆