#include <stdio.h>
#include <clocale>
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
//编译连接加上 -fexec-charset=gbk -finput-charset=gbk
const char* psa = "A汉字ABC";
const wchar_t* psw = L"W汉字ABC";
string UnicodeToANSI(const wstring& str)
{
char *pStr;
int iwstrLen = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, 0, 0, 0, 0);
cout << "iwstrlen=" << iwstrLen << endl;
pStr = new char[iwstrLen +1];
memset(pStr, 0, sizeof(char)*(iwstrLen + 1));
WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, pStr, iwstrLen, 0, 0);
string strText;
strText = pStr;
delete pStr;
cout << "转换ANSI完成" << endl;
return strText;
}
wstring ANSItoUnicode(const string& str)
{
wchar_t *pwstr;
int istrLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, 0, 0);
cout << "istrlen=" << istrLen << endl;
pwstr = new wchar_t[istrLen + 1]{0};
memset(pwstr, 0, (istrLen + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pwstr, istrLen);
wstring wTemp = pwstr;
delete pwstr;
cout << "转换Unicode完成" << endl;
return wTemp;
}
int main(int argc, char* argv[])
{
ios::sync_with_stdio(false); // Linux gcc.
// locale::global(locale(""));
wcout.imbue(locale(""));
setlocale(LC_CTYPE, ""); // MinGW gcc.
// wcout.imbue(locale(locale(), "", LC_CTYPE));
// C++
cout <<"C++:\n"<< endl;
cout << psa << endl;
wcout << psw << endl;
wcout << 12345 << endl;
wstring str = ANSItoUnicode(psa);
wcout << str.length() << endl << str << endl;
string str1 = UnicodeToANSI(psw);
cout << str1.length() << endl << str1 << endl;
// C
printf("\n\nC:\n");
printf("\t%s\n", psa);
printf("\t%ls\n", psw);
wprintf(L"\t%s\n", psw);
return 0;
}