天天看點

關于c++中utf8和gbk編碼方式的轉換

GBK轉utf8如下:

string GBKToUTF8(const std::string& strGBK)  
{  
    string strOutUTF8 = "";  
    WCHAR * str1;  
    int n = MultiByteToWideChar(CP_ACP, , strGBK.c_str(), -, NULL, );  
    str1 = new WCHAR[n];  
    MultiByteToWideChar(CP_ACP, , strGBK.c_str(), -, str1, n);  
    n = WideCharToMultiByte(CP_UTF8, , str1, -, NULL, , NULL, NULL);  
    char * str2 = new char[n];  
    WideCharToMultiByte(CP_UTF8, , str1, -, str2, n, NULL, NULL);  
    strOutUTF8 = str2;  
    delete[]str1;  
    str1 = NULL;  
    delete[]str2;  
    str2 = NULL;  
    return strOutUTF8;  
}  
           

utf8轉GBK如下:

string UTF8ToGBK(const std::string& strUTF8)  
{  
    int len = MultiByteToWideChar(CP_UTF8, , strUTF8.c_str(), -, NULL, );  
    unsigned short * wszGBK = new unsigned short[len + ];  
    memset(wszGBK, , len *  + );  
    MultiByteToWideChar(CP_UTF8, , (LPCTSTR)strUTF8.c_str(), -, wszGBK, len);  

    len = WideCharToMultiByte(CP_ACP, , wszGBK, -, NULL, , NULL, NULL);  
    char *szGBK = new char[len + ];  
    memset(szGBK, , len + );  
    WideCharToMultiByte(CP_ACP,, wszGBK, -, szGBK, len, NULL, NULL);  
    //strUTF8 = szGBK;  
    std::string strTemp(szGBK);  
    delete[]szGBK;  
    delete[]wszGBK;  
    return strTemp;  
}  
           

C++頭檔案包含檔案:

#include <iostream>  
#include <string>  
#include <fstream>  
#include <windows.h> 
           

繼續閱讀