Window下wchar_t与char字符串之间的转换
static std::string WCharToAnsi(const wchar_t* src) {
std::string ret = "";
const auto size = WideCharToMultiByte(CP_ACP, 0, src, -1, nullptr, 0, nullptr, nullptr);
if (size > 0) {
char* dest = new char[size];
if (nullptr != dest) {
WideCharToMultiByte(CP_ACP, 0, src, -1, dest, size, nullptr, nullptr);
ret = dest;
delete[] dest;
}
}
return ret;
}
static std::wstring AnsiToWChar(const char* src) {
std::wstring ret = L"";
const auto size = MultiByteToWideChar(CP_ACP, 0, src, -1, nullptr, 0);
if (size > 0) {
wchar_t* dest = new wchar_t[size];
if (nullptr != dest) {
MultiByteToWideChar(CP_ACP, 0, src, -1, dest, size);
ret = dest;
delete[] dest;
}
}
return ret;
}
std::string WCharToUTF8(const wchar_t* src) {
std::string ret = "";
const auto size = WideCharToMultiByte(CP_UTF8, 0, src, -1, nullptr, 0, nullptr, nullptr);
if (size > 0) {
char* dest = new char[size];
if (nullptr != dest) {
WideCharToMultiByte(CP_UTF8, 0, src, -1, dest, size, nullptr, nullptr);
ret = dest;
delete[] dest;
}
}
return ret;
}
std::wstring UTF8ToWChar(const char* src) {
std::wstring ret = L"";
const auto size = MultiByteToWideChar(CP_UTF8, 0, src, -1, nullptr, 0);
if (size > 0) {
wchar_t* dest = new wchar_t[size];
if (nullptr != dest) {
MultiByteToWideChar(CP_UTF8, 0, src, -1, dest, size);
ret = dest;
delete[] dest;
}
}
return ret;
}
1 int main() { 2 std::wcout.imbue(std::locale("chs")); 3 4 const char* str = "*你好abc123#"; 5 const wchar_t* wstr = L"*你好abc123#"; 6 7 auto dest1 = WChar2Ansi(wstr); 8 auto wdest2 = Ansi2WChar(str); 9 10 std::cout << "S1: " << dest1 << std::endl; 11 std::wcout << L"S2: "<<wdest2 << std::endl; 12 13 return 0; 14 }
测试环境:Windows 7 and VS2015
以后需要就来这里copy。再也不想写这样的代码了QAQ。
另外补充:如果想在控制台中用std::wcout输出中文,需要先加一句“ std::wcout.imbue(std::locale("chs")); ” 进行设定。
更多信息可以查看这里:https://blog.csdn.net/dahaiyudong/article/details/82533574