尝试打印 unicode 字符 C++ 断言失败

问题描述

我一直在尝试打印 Unicode 字符。我是 C++ 的新手。我使用的是 Windows 10 并使用 Visual Studio 2019。

我正在尝试在控制台应用程序中打印以下艺术作品:

██╗███╗░░██╗░██████╗░█████╗░███╗░░██╗██╗████████╗██╗░░░██╗
██║████╗░██║██╔════╝██╔══██╗████╗░██║██║╚══██╔══╝╚██╗░██╔╝
██║██╔██╗██║╚█████╗░███████║██╔██╗██║██║░░░██║░░░░╚████╔╝░
██║██║╚████║░╚═══██╗██╔══██║██║╚████║██║░░░██║░░░░░╚██╔╝░░
██║██║░╚███║██████╔╝██║░░██║██║░╚███║██║░░░██║░░░░░░██║░░░
╚═╝╚═╝░░╚══╝╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░░╚═╝░░░░░░╚═╝░░░

我使用了 _setmode(_fileno(stdout),_O_U16TEXT); 来打印它,但是当我尝试打印一些文本时,我得到一个断言失败。

我的代码是这样的:

#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <Windows.h>

void banner() {

    _setmode(_fileno(stdout),_O_U16TEXT);
    wprintf(L"      ██╗███╗░░██╗░██████╗░█████╗░███╗░░██╗██╗████████╗██╗░░░██╗\n");
    wprintf(L"      ██║████╗░██║██╔════╝██╔══██╗████╗░██║██║╚══██╔══╝╚██╗░██╔╝\n");
    wprintf(L"      ██║██╔██╗██║╚█████╗░███████║██╔██╗██║██║░░░██║░░░░╚████╔╝░\n");
    wprintf(L"      ██║██║╚████║░╚═══██╗██╔══██║██║╚████║██║░░░██║░░░░░╚██╔╝░░\n");
    wprintf(L"      ██║██║░╚███║██████╔╝██║░░██║██║░╚███║██║░░░██║░░░░░░██║░░░\n");
    wprintf(L"      ╚═╝╚═╝░░╚══╝╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░░╚═╝░░░░░░╚═╝░░░\n");
}
void login(std::string username,std::string password) {

}
void menu() {
    printf("Thank you For choosing Insanity");
}
int main()
{
    bool loggedin = false;
    if (loggedin) {
        banner();
        menu();

    }
    else {
        banner();
        printf("Please Login...\n");
        printf("Username :");
    }
    return 0;
}

在这里遗漏了什么?

解决方法

我认为将模式和 coutwcout 混合使用不是一个好主意。

您可以尝试只使用 std::wcout 并在程序启动时直接设置模式 - 在您进行任何输出之前。

这可能有效:

#include <fcntl.h>
#include <io.h>
#include <Windows.h>

#include <clocale>
#include <iostream>
#include <string>

const std::wstring greeting =
LR"aw(
██╗███╗░░██╗░██████╗░█████╗░███╗░░██╗██╗████████╗██╗░░░██╗
██║████╗░██║██╔════╝██╔══██╗████╗░██║██║╚══██╔══╝╚██╗░██╔╝
██║██╔██╗██║╚█████╗░███████║██╔██╗██║██║░░░██║░░░░╚████╔╝░
██║██║╚████║░╚═══██╗██╔══██║██║╚████║██║░░░██║░░░░░╚██╔╝░░
██║██║░╚███║██████╔╝██║░░██║██║░╚███║██║░░░██║░░░░░░██║░░░
╚═╝╚═╝░░╚══╝╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░░╚═╝░░░░░░╚═╝░░░
)aw";

void banner() {
    std::wcout << greeting;
}

void menu() {
    std::wcout << L"Thank you For choosing Insanity";
}

int main() {
    const char CP_UTF_16LE[] = ".1200";
    setlocale(LC_ALL,CP_UTF_16LE);
    _setmode(_fileno(stdout),_O_U16TEXT);

    bool loggedin = false;
    if (loggedin) {
        banner();
        menu();
    } else {
        banner();
        std::wcout << L"Please Login...\nUsername :";
    }
}