//把字符串转换成宽字符串
02
wstring string2Wstring(string sToMatch)
03
{
04
#ifdef _A_WIN
05
intiWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 );// 计算转换后宽字符串的长度。(不包含字符串结束符)
06
wchar_t*lpwsz = newwchar_t [iWLen + 1];
07
MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式转换。
08
lpwsz[iWLen] = L'/0';
09
wstring wsToMatch(lpwsz);
10
delete[]lpwsz;
11
#elif _A_LINUX
12
setlocale( LC_CTYPE, ""); // 很重要,没有这一句,转换会失败。
13
intiWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 计算转换后宽字符串的长度。(不包含字符串结束符)
14
wchar_t*lpwsz = newwchar_t[iWLen + 1];
15
inti = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 转换。(转换后的字符串有结束符)
16
wstring wsToMatch(lpwsz);
17
delete[]lpwsz;
18
#endif
19
returnwsToMatch;
20
}
21
//把宽字符串转换成字符串,输出使用
22
string wstring2string(wstring sToMatch)
23
{
24
#ifdef _A_WIN
25
string sResult;
26
intiLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE );// 计算转换后字符串的长度。(包含字符串结束符)
27
char*lpsz = newchar[iLen];
28
WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); // 正式转换。
29
sResult.assign( lpsz, iLen - 1 ); // 对string对象进行赋值。
30
delete[]lpsz;
31
#elif _A_LINUX
32
intiLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 计算转换后字符串的长度。(不包含字符串结束符)
33
char*lpsz = newchar[iLen + 1];
34
inti = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 转换。(没有结束符)
35
lpsz[iLen] = '/0';
36
string sResult(lpsz);
37
delete[]lpsz;
38
#endif
39
returnsResult;
40
}
转自:http://bbs.unix8.net/thread-233-1-1.html