最近,我想写一下我的API的客户端,供Windows开发者使用,可是在开发的时候遇到了一个问题:输出中文会乱码,仔细一想,感觉是编码的锅,cmd用UFT8编码后可以解决,于是我打算让其自动转换其字符类型

下面是代码,源于网上,找了好久找到的,修了几个bug和一些代码,仅供参考吧

[c] #include #include #include #include #include using namespace std; string GbkToUtf8(const char* src_str) { int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0); wchar_t* wstr = new wchar_t[len + 1]; memset(wstr, 0, len + 1); MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len); len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL); string strTemp = str; if (wstr) delete[] wstr; if (str) delete[] str; return strTemp; } string Utf8ToGbk(const char* src_str) { int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0); wchar_t* wszGBK = new wchar_t[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, src_str, -1, wszGBK, len); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); char* szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); string strTemp(szGBK); if (wszGBK) delete[] wszGBK; if (szGBK) delete[] szGBK; return strTemp; } int main(void) { const char* src_str = “这是一个测试”; printf(“\n源文本:”); printf(src_str); printf(“\ngbk to uft8:”); printf(GbkToUtf8(src_str).c_str()); printf(“\nuft8 to gbk:”); printf(Utf8ToGbk(src_str).c_str()); return 0; } [/c]

目前代码测试是没有问题的,如果有问题欢迎指出!


广告
广告正在加载中...
暂不开放评论,如对本文有任何疑问,请联系i#mr-wu.top(#替换为@)