.
实现过程
.
#include "stdafx.h" #include <windows.h> #include <iostream> #include <string> using namespace std; string Unicode2Ascii(wstring wstrsrc); wstring Ascii2Unicode(string astrsrc); string Unicode2UTF8(wstring wstrsrc); wstring UTF82Unicode(string utf8strsrc); int main(int argc, char* argv[]) { char szText[] = "这是一个ANSI转化为UTF8的例子!\r\n"; wstring strUnicode; string strAnsi, strUTF8; strAnsi = szText; strUnicode = Ascii2Unicode(strAnsi); strUTF8 = Unicode2UTF8(strUnicode); cout << strUTF8 << endl; strUnicode = UTF82Unicode(strUTF8); strAnsi = Unicode2Ascii(strUnicode); cout << strAnsi << endl; return 0; } string Unicode2Ascii(wstring wstrsrc) { int nLength = ::WideCharToMultiByte(CP_OEMCP, 0, wstrsrc.c_str(), -1, NULL, 0, NULL, NULL); if(nLength <= 0) return string(""); char *szbuffer = new char[nLength + 2]; ::WideCharToMultiByte(CP_OEMCP, 0, wstrsrc.c_str(), -1, szbuffer, nLength, NULL, NULL); string strnew = szbuffer; delete [] szbuffer; return strnew; } wstring Ascii2Unicode(string astrsrc) { int nLength = ::MultiByteToWideChar(CP_ACP, 0, astrsrc.c_str(), -1, NULL, 0); if(nLength <= 0) return wstring(L""); wchar_t *szbuffer = new wchar_t[nLength + 2]; ::MultiByteToWideChar(CP_ACP, 0, astrsrc.c_str(), -1, szbuffer, nLength); wstring strnew = szbuffer; delete [] szbuffer; return strnew; } string Unicode2UTF8(wstring wstrsrc) { int nLength = ::WideCharToMultiByte(CP_UTF8, 0, wstrsrc.c_str(), -1, NULL, 0, NULL, NULL); if(nLength <= 0) return string(""); char *szbuffer = new char[nLength + 2]; ::WideCharToMultiByte(CP_UTF8, 0, wstrsrc.c_str(), -1, szbuffer, nLength, NULL, NULL); string strnew = szbuffer; delete [] szbuffer; return strnew; } wstring UTF82Unicode(string utf8strsrc) { int nLength = ::MultiByteToWideChar(CP_UTF8, 0, utf8strsrc.c_str(), -1, NULL, 0); if(nLength <= 0) return wstring(L""); wchar_t *szbuffer = new wchar_t[nLength + 2]; ::MultiByteToWideChar(CP_UTF8, 0, utf8strsrc.c_str(), -1, szbuffer, nLength); wstring strnew = szbuffer; delete [] szbuffer; return strnew; } |
.
|
.
图
.
备注
.
.关键点
.
相关链接
相关链接 相关链接
相关链接 相关链接.
.