使用C++在控制台中输出Unicode字符

3

Windows 8 x64; Visual Studio 2012;

我通过书籍学习C++。在这个论坛上,我发现了许多主题关于如何通过C++读写Unicode字符串。但是这些主题并没有被标记为已解决(???)。这真的是C++中的一个很大的问题吗?我尝试了不同的变体 - 它们对我都不起作用:

#include<iostream>
#include<Windows.h>
#include <io.h>
#include <fcntl.h>
using namespace std;

int main() {
    // variant 1:
    wcout << L"Hello World!" << endl; // displayed
    wcout << L"Привет Мир!" << endl;// not displayed

    //**********************************************

    // variant 2:
    SetConsoleOutputCP(CP_UTF8);
    wchar_t s[] = L"Hello World (2)!";
    int bufferSize = WideCharToMultiByte(CP_UTF8, 0, 
        s, -1, NULL, 0, NULL, NULL);
    char* m = new char[bufferSize]; 
    WideCharToMultiByte(CP_UTF8, 0, s, -1, m, 
        bufferSize, NULL, NULL);

    wprintf(L"%S", m); // valid output
    wcout << endl;
    printf("%s", m); // valid output
    wcout << endl;

    wchar_t s2[] = L"Привет мир (2)!";
    int bufferSize2 = WideCharToMultiByte(CP_UTF8, 0, 
        s2, -1, NULL, 0, NULL, NULL);
    char* m2 = new char[bufferSize2]; 
    WideCharToMultiByte(CP_UTF8, 0, s2, -1, m2, 
        bufferSize2, NULL, NULL);

    wprintf(L"%S", m2); // invalid output
    wcout << endl;
    printf("%s", m2); // invalid output
    wcout << endl;
    //**********************************************

    // variant 3 (not working):
    _setmode(_fileno(stdout), _O_U16TEXT);
    wcout << L"Testing unicode -- English -- Ελληνικά"
        << "-- Español." << endl;

    return 0;
}

但它仅适用于英文字符... 屏幕:

enter image description here

如何通过C++解决这个问题?

离题了,但是你怎么能让Windows 8的窗口角落弯曲呢? - phuclv
4个回答

2
我找到了一个更简单的方法(不需要更改代码页和字体):

我发现更简单的变体(无需更改代码页和字体):

#include<iostream>
#include<windows.h>

using namespace std;
int main()
{
    cout<<"Привет мир (1)!" << endl; // invalid output

    SetConsoleCP(GetACP());
    SetConsoleOutputCP(GetACP());

    cout<<"Привет мир (2)!" << endl; // valid output!

    return 0;
}

也许这不仅对我有趣。
P.S. 但是......它在CMD.EXE中可以工作,但在POWERSHELL.EXE中不起作用。

2

谢谢。我在运行我的EXE文件之前尝试了它,但结果仍然是一样的。:((( - Andrey Bushman
1
@Bush,我忘了告诉你需要使用 cmd.exe 属性将控制台字体切换为 Lucida。很高兴听到这是否奏效。 - Dmytro Sirenko
不要忘记将控制台字体切换为Lucide。是的,现在它可以工作了!谢谢! - Andrey Bushman
1
我相信 SetConsoleOutputCP(CP_UTF8); 部分地实现了与 chcp 65001 相同的功能。 - bames53
如果您查找Boost.Nowide,您可以使用它来得到一个不错的解决方案。 - Jookia

0

我发现使用以下命令比chcp命令更清晰明了:

// Getting the readable Cyrillic chars in the console window...
setlocale(LC_ALL, "Russian");
wcout << endl << L"Добро "; // UNICODE
cout << "пожаловать!" << endl; // ANSI

对于这两种情况,我都能得到可读的输出。


-1

哦~~对不起,以下是 C 语言。

在 C++ 中你可以这样做:

#include <iostream>
#include <locale>
using namespace std;
int main(int argc, char *argv[])
{
    locale::global(std::locale(""));
    wcout << L"Привет Мир!" << endl;
    return 0;
}

#include <locale.h>

setlocale(LC_ALL,NULL);

默认设置为(LC_ALL,“C”)。因此,您无法显示除ASCII代码以外的字符。


谢谢。我将其添加到我的CPP文件中,重新构建了它,但结果仍然相同。 :((( 那些不会说英语的人是如何解决这个问题的? - Andrey Bushman
可能是因为cmd.exe无法完全支持Unicode,所以在显示Unicode字符时出现了一些问题。 - hbprotoss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接