使用WriteConsoleW打印Unicode日语字符

Printing Unicode Japanese characters with WriteConsoleW

本文关键字:日语 字符 Unicode 打印 WriteConsoleW 使用      更新时间:2023-10-16

所以,我正在尝试打印一些日语字符。我尽了一切可能。我错过了什么?

#include <windows.h>
#include <string>
template<typename T>
void printW(const T* text) {
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), text, std::char_traits<T>::length(text), 0, 0);
}
template<typename T>
void print(const T* text) {
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), text, std::char_traits<T>::length(text), 0, 0);
}
int main() 
{
    //const char* text = "こんにちはn";
    const wchar_t* textL = L"こんにちはn";
    const char16_t* textu = u"こんにちはn";
    const char32_t* textU = U"こんにちはn";
    //printW(text);
    printW(textL);
    printW(textu);
    printW(textU);
}

不需要WinAPI,而且您使用了错误的类型。

#include <iostream>
#include <string>
int main() 
{
    std::string text{u8"こんにちは"};
    std::cout << text;
}

实例

如果您需要使用WinAPI,则需要最少的修改:

#include <windows.h>
#include <string>
template<typename T>
void print(const T* text) {
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), text, std::char_traits<T>::length(text), 0, 0);
}
int main() 
{
    auto text = u8"こんにちはn";
    print(text);
}  

免责声明:未在实际的windows机器上测试