C++中如何将wchar_t转换为string

如题,或者把wchar_t转换为char也行,急!!!
2025-02-27 14:26:30
推荐回答(1个)
回答1:

#include
#include

#include
#include

using namespace std;

int main()
{
std::string szDst;

wchar_t wText[20] = {L"China 中国"};
DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);

char *psText;
psText = new char[dwNum];
WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);
szDst = psText;

// 删除临时变量
delete []psText;

// 输出
cout << szDst << endl;

return 0;

}

我也是网上参考改的,如果没有Unicode只有Ascii的话,可以直接用循环按每个字符进行char的强制转换即可