文号
t71972
阅读
3451
回复
2
收藏
2
适用于Visual C++的转码函数
2015/06/11
IP:四川
由于历史遗留问题,在Visual C++中编码通常是比较令人头疼的问题

程序内码是编译时定义的,Windows的窗口注册时所用的字符编码,一般分为ANSI/MBCS(中文系统是GBK)或Unicode。

GBK - 程序内码之间的转换是非常简单的,因为CString本身就有转码功能。

GBK转换为程序内码
CString str1 = (CString) gbk_str;
程序内码转换为GBK
CStringA gbk_str = (CStringA) str1;

Unicode转换为程序内码
CString str1 = (CString) unicode_str;
程序内码转换为Unicode
CStringW unicode_str = (CStringW) str1;

UTF-8转码则需要使用WinAPI函数MultiByteToWideChar和WideCharToMultiByte,但是使用有点麻烦,可以写两个函数封装转码过程。

使用方法1:UTF-8转换为程序内码
CString str3 = mbcs2tcs(utf8_str, true);
使用方法2:程序内码转换为UTF-8
CStringA utf8_str = tcs2mbcs(str3, true);
CString mbcs2tcs(CStringA astr, bool isutf8)
{
    if (isutf8) {
        int length = MultiByteToWideChar(CP_UTF8, 0, astr, -1, NULL, 0);
        wchar_t *bufnew = new wchar_t[length + 1];
        MultiByteToWideChar(CP_UTF8, 0, astr, -1, bufnew, length);
        bufnew[length] = 0;
        CString wstr(bufnew);
        delete []bufnew;
        return wstr;
    }
    else {
        return (CString) astr;
    }
}
 
CStringA tcs2mbcs(CString str, bool isutf8)
{
    if (isutf8) {
        CStringW wstr = (CStringW) str;
        int length = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
        char *bufnew = new char[length + 1];
        WideCharToMultiByte(CP_UTF8, 0, wstr, -1, bufnew, length, NULL, NULL);
        bufnew[length] = 0;
        CStringA astr(bufnew);
        delete []bufnew;
        return astr;
    }
    else {
        return (CStringA) str;
    }
}
[ 修改于11年6个月前 - 2015/06/12 09:51:25 ]
来自:
软件综合
2
acmilan作者
11年6个月前修改于 11年6个月前IP:四川
772821
1楼
Unicode编译版本下
CString:
在以CFile::typeText打开的文件,ReadString()、WriteString()读写Unicode文档(typeText将"\n\0"替换为"\r\0\n\0")
在以CFile::typeText打开的文件,Read()、Write()读写MBCS文档(typeText将"\n"替换为"\r\n")
在以CFile::typeBinary打开的文件,ReadString()、WriteString()读写Unicode文档
在以CFile::typeBinary打开的文件,Read()、Write()读写任何文档
CStringA:
可以通过Read()、Write()读写,但是不能通过ReadString()、WriteString()读写。
CStringW:
在以CFile::typeText打开的文件,可以通过ReadString()、WriteString()读写,而不能通过Read()、Write()读写。(换行符会出问题)
在以CFile::typeBinary打开的文件,可以通过ReadString()、WriteString()、Read()、Write()读写。

MBCS编译版本下
CString:
在以CFile::typeText打开的文件,Read()、Write()、ReadString()、WriteString()均读写MBCS文档(typeText将"\n"替换为"\r\n")
在以CFile::typeBinary打开的文件,ReadString()、WriteString()读写MBCS文档
在以CFile::typeBinary打开的文件,Read()、Write()读写任何文档
CStringA:
可以通过Read()、Write()、ReadString()、WriteString()读写。
CStringW:
在以CFile::typeText打开的文件,无法正常读写。
在以CFile::typeBinary打开的文件,可以通过Read()、Write()读写,但是不能通过ReadString()、WriteString()读写。
引用
评论
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的