C++宽字符串转字符串
这文章是更改别人代码
#include <string>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <locale>
#include <locale.h>
#define _A_WIN //如果你是windows
using namespace std;
//把字符串转换成宽字符串
wstring string_wstring(string sToMatch)
{
#ifdef _A_WIN
int iWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 ); // 计算转换后宽字符串的长度。(不包含字符串结束符)
wchar_t *lpwsz = new wchar_t [iWLen + 1];
MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); // 正式转换。
lpwsz[iWLen] = L'\0';
wstring wsToMatch(lpwsz);
delete []lpwsz;
return wsToMatch;
#elifdef _A_LINUX
setlocale( LC_CTYPE, "" ); // 很重要,没有这一句,转换会失败。
int iWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); // 计算转换后宽字符串的长度。(不包含字符串结束符)
wchar_t *lpwsz = new wchar_t[iWLen + 1];
int i = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); // 转换。(转换后的字符串有结束符)
wstring wsToMatch(lpwsz);
delete []lpwsz;
return wsToMatch;
#endif
//return wsToMatch;
return NULL;
}
//把宽字符串转换成字符串,输出使用
string wstring_string(wstring sToMatch)
{
#ifdef _A_WIN
string sResult;
int iLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE ); // 计算转换后字符串的长度。(包含字符串结束符)
char *lpsz = new char[iLen];
WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); // 正式转换。
sResult.assign( lpsz, iLen - 1 ); // 对string对象进行赋值。
delete []lpsz;
return sResult;
#elifdef _A_LINUX
int iLen = wcstombs( NULL, sToMatch.c_str(), 0 ); // 计算转换后字符串的长度。(不包含字符串结束符)
char *lpsz = new char[iLen + 1];
int i = wcstombs( lpsz, sToMatch.c_str(), iLen ); // 转换。(没有结束符)
lpsz[iLen] = '\0';
string sResult(lpsz);
delete []lpsz;
return sResult;
#endif
//return sResult;
return NULL;
}
更改
wstring string_wstring(string sToMatch):return wsToMatch;
string wstring_string(wstring sToMatch):return sResult;
wstring string_wstring(string sToMatch):lpwsz[iWLen] = L'\0';
string wstring_string(wstring sToMatch):lpsz[iLen] = '\0';
#elif:#elifdef;
博客园博客只做备份,博客发布就不再更新,如果想看最新博客,请访问 https://blog.lindexi.com/
如图片看不见,请在浏览器开启不安全http内容兼容
![知识共享许可协议](https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png)
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名[林德熙](https://www.cnblogs.com/lindexi)(包含链接:https://www.cnblogs.com/lindexi ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我[联系](mailto:lindexi_gd@163.com)。