C++中,宽窄字符互换(wchar_t char wstring string互换)

宽字符转窄字符(wstring转string):

std::string WstringToString(const std::wstring& sInput) {
    if (sInput.length() == 0)
        return "";
    int iBufLen = WideCharToMultiByte(CODE_PAGE, 0, sInput.c_str(), -1, NULL, 0, NULL, NULL);
    char* buf = new char[iBufLen + 1];
    int iLen = WideCharToMultiByte(CODE_PAGE, 0, sInput.c_str(), -1, buf, iBufLen + 1, NULL, NULL);
    std::string sOutput(buf, iLen);
    delete[] buf;
    return sOutput;
}

窄字符转宽字符(string转wstring):

std::wstring utils::StringToWstring(const std::string& sInput) {
    if (sInput.length() == 0)
        return L"";
    int iBufLen = MultiByteToWideChar(CODE_PAGE, 0, sInput.c_str(), -1, NULL, 0);
    wchar_t* buf = new wchar_t[iBufLen + 1];
    int iLen = MultiByteToWideChar(CODE_PAGE, 0, sInput.c_str(), -1, buf, iBufLen + 1);
    std::wstring sOutput(buf, iLen);
    delete[] buf;
    return sOutput;
}

其中,涉及到wchar_t,char_t的转换,可由上面的函数修改一二可得。

posted @   silomen  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示