GBK到UTF8编码转换C++实现 GBK到UTF8编码转换C++实现



GBK到UTF8编码转换C++实现

  1. #include <iostream>  
  2. #include <string>  
  3. #include <fstream>  
  4. #include <windows.h>   
  5.   
  6. using namespace std;  
  7.   
  8. string GBKToUTF8(const std::string& strGBK)  
  9. {  
  10.     string strOutUTF8 = "";  
  11.     WCHAR * str1;  
  12.     int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);  
  13.     str1 = new WCHAR[n];  
  14.     MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);  
  15.     n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);  
  16.     char * str2 = new char[n];  
  17.     WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);  
  18.     strOutUTF8 = str2;  
  19.     delete[]str1;  
  20.     str1 = NULL;  
  21.     delete[]str2;  
  22.     str2 = NULL;  
  23.     return strOutUTF8;  
  24. }  
  25.   
  26. string UTF8ToGBK(const std::string& strUTF8)  
  27. {  
  28.     int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);  
  29.     unsigned short * wszGBK = new unsigned short[len + 1];  
  30.     memset(wszGBK, 0, len * 2 + 2);  
  31.     MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUTF8.c_str(), -1, wszGBK, len);  
  32.   
  33.     len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);  
  34.     char *szGBK = new char[len + 1];  
  35.     memset(szGBK, 0, len + 1);  
  36.     WideCharToMultiByte(CP_ACP,0, wszGBK, -1, szGBK, len, NULL, NULL);  
  37.     //strUTF8 = szGBK;  
  38.     std::string strTemp(szGBK);  
  39.     delete[]szGBK;  
  40.     delete[]wszGBK;  
  41.     return strTemp;  
  42. }  
  43.   
  44. int _tmain(int argc, _TCHAR* argv[])  
  45. {  
  46.     string test("我们中国是个强大的名族,强大的动力来自每个人的支持");  
  47.     fstream output("test.txt",ios_base::out | ios_base::app);  
  48.     output << GBKToUTF8(test);  
  49.     //system("iconv -f GBK -t utf-8");  
  50.     return 0;  
  51. }  

猜你喜欢

转载自blog.csdn.net/qq_25408423/article/details/80649397