转自 http://topic.csdn.net/u/20090414/11/ea7ffb2d-82fb-4504-b1f9-77560f0dceae.html?88949
- include "stdafx.h"
- #include "windows.h"
- #include <string>
- #include <fstream>
- #include <iostream>
- using namespace std;
- //从Unicode到UTF8
- string ToUTF8(wstring str)
- {
- char* buff;
- int buffersize=WideCharToMultiByte(CP_UTF8,0,str.c_str(),(int)str.length(),0,0,0,0); //获取需要的输出缓冲区长度
- buff=new char[buffersize+1];
- WideCharToMultiByte(CP_UTF8,0,str.c_str(),(int)str.length(),buff,buffersize+1,0,0);
- buff[buffersize]=0;
- string utf=buff;
- delete []buff;
- return(utf);
- }
- //从Unicode到Ansi
- string ToString(wstring str)
- {
- char *buff=new char[str.length()+1];
- int i=WideCharToMultiByte(CP_ACP,0,str.c_str(),str.length(),buff,str.length()+1,0,0);
- buff[i]=0;
- string text=buff;
- delete [] buff;
- return(text);
- }
- //从UTF8到Unicode
- wstring FromUTF8(string utf)
- {
- wchar_t *buff=new wchar_t[utf.length()+1];
- int i=MultiByteToWideChar(CP_UTF8, 0, utf.c_str(),-1, buff, (int)utf.length());
- buff[i+1]=0;
- wstring str=buff;
- delete [] buff;
- return(str);
- }
- //从Ansi到Unicode
- wstring ToString(string str)
- {
- wchar_t *buff=new wchar_t[str.length()+1];
- MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, buff, str.length()+1);
- wstring text=buff;
- delete [] buff;
- return(text);
- }
- void main()
- {
- string asc="abcd这是一个ASCII字符串";
- wstring unicode=ToString(asc); //toString有两个重载,分别是Ascii to Unicode 和Unicode to Ascii
- string utf8=ToUTF8(unicode);
- wstring utf16=FromUTF8(utf8);
- ofstream ofs("D://01.txt");
- ofs < <utf8.c_str() < <'/n';
- ofs.close();
- system("pause");
- }