ANSI转UTF-8

来源:互联网 发布:mac系统最大化快捷键 编辑:程序博客网 时间:2024/05/29 17:31

说明:

记事本txt有四种编码方式,分别为:UTF-8、ANSI、Unicode和Unicode big endian,当进行写操作,创建的txt编码格式,与写入汉字的编码方式相同;如果写入的汉字是不同的编码方式,此时创建的txt中,会出现乱码,所以需要把汉字转化为同一编码方式。

本文主要介绍:把汉字编码方式,由ANSI方式转化为UTF-8方式:

一、ANSI转化为UTF-8程序:

 

CString ToUTF8(const wchar_t* buffer, int len)  //返回类型为CString

    int size = ::WideCharToMultiByte(CP_UTF8, 0, buffer, len, NULL, 0, NULL, 
            NULL); 
    if (size == 0) 
        return ""; 
 
    std::string newbuffer; 
    newbuffer.resize(size); 
    ::WideCharToMultiByte(CP_UTF8, 0, buffer, len, 
            const_cast<char*>(newbuffer.c_str()), size, NULL, NULL); 
 
 //如需返回string类型,直接 return newbuffer
 
 TCHAR outstr[64]; //string 转化为CString返回
 CString strTemp;
 memset(outstr, '\0', sizeof(outstr));
 memcpy(outstr,newbuffer.c_str(),newbuffer.size());
 strTemp.Format("%s",outstr);
 return strTemp;

二、函数调用形式

wstring text =  L"汉字";
CString strTemp = ToUTF8(text.c_str(),text.size());

原创粉丝点击