【方法】使C++的cout能在不设置locale的情况下正确输出wchar_t Unicode字符串

时间:2023-01-06 20:17:40
通过重载cout的<<运算符即可实现。
【程序】
#include <iostream>
#include <Windows.h>

using namespace std;

// 使C++的cout能输出Unicode字符串
ostream &operator << (ostream &os, const wchar_t *wstr)
{
if (os == cout)
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), wstr, wcslen(wstr), NULL, NULL);
return os;
}

int main(void)
{
cout << L"简体中文abc" << endl << L"¿Cómo estás?" << endl;
return 0;
}


【运行结果】

【方法】使C++的cout能在不设置locale的情况下正确输出wchar_t Unicode字符串