测试环境: vs2008
开发语言:C++
#include <iostream>
#include <windows.h>
#include
<string>
// wchar_t to string
void
Wchar_tToString(std::string& szDst, wchar_t *wchar)
{
wchar_t *
wText = wchar;
DWORD dwNum =
WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);//
WideCharToMultiByte的运用
char *psText; //
psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new
char[dwNum];
WideCharToMultiByte
(CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);//
WideCharToMultiByte的再次运用
szDst = psText;// std::string赋值
delete
[]psText;// psText的清除
}
// string to
wstring
void StringToWstring(std::wstring& szDst,
std::string str)
{
std::string temp = str;
int
len=MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1,
NULL,0);
wchar_t * wszUtf8 = new
wchar_t[len+1];
memset(wszUtf8, 0, len * 2 +
2);
MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1,
(LPWSTR)wszUtf8, len);
szDst = wszUtf8;
std::wstring r =
wszUtf8;
delete[] wszUtf8;
}
int main(int argc, char
*argv)
{
// wchar_t to string
std::string
szDest;
wchar_t wText[20] =
{L"宽字符转换字符串实例!OK!"};
Wchar_tToString(szDest,
wText);
std::cout<<"szDest:
"<<szDest<<std::endl;
/**
*wchar_t
定义的变量为什么不能输出呢?
*宽字符类型要本地化,否则输不出想要结果。
*本地化有三条语句可以使用,任取其一。最后一句是全局函数,前两个是wcout的一个成员函数的两种表达方式。
*/
//std::wcout.imbue(std::locale("chs"));
//std::wcout.imbue(std::locale(""));
setlocale(LC_ALL,"Chinese-simplified");
// string to wstring
std::string szSrc =
"字符串转换宽字符实例!OK!";
std::wstring wszDest;
StringToWstring(wszDest,
szSrc);
std::wcout << "wszDest: " << wszDest <<
std::endl;
/**
string to wchar_t
*/
string str= "字符串转换宽字符实例!OK!";
std::wstring widstr =
std::wstring(str.begin(), str.end());
const wchar_t *pwidstr =
widstr.c_str();
// 此方法简单,但是 delete wc;时会出异常
wchar_t *
wc = new
wchar_t[szSrc.size()];
swprintf(wc,L"%S
",szSrc.c_str());//注意大写S。。
std::wcout <<"szSrc: " << wc
<<std::endl;
//delete wc;
system("PAUSE");
}