简体   繁体   English

为什么我的C ++程序输出乱码

[英]Why does my c++ program output garbled code

I use MinGW64 to compile c++ programs. 我使用MinGW64编译c ++程序。 But since I upgraded to Windows 10, I found my c program output Chinese will be garbled code. 但是自从我升级到Windows 10以来,我发现我的c程序输出中文将是乱码。

I follow the online method, adding a code in the program header: SetConsoleOutputCP(65001); 我遵循在线方法,在程序头中添加了代码: SetConsoleOutputCP(65001); , then it fixes. ,然后修复。 but I think it's so troublesome to do this for each c++ program. 但是我认为为每个c ++程序执行此操作非常麻烦。 What should I do? 我该怎么办?

I think this is my system's problem, the same code in Windows 7 is not a problem, I just want to find a more convenient solution instead of adding the same code to every file 我认为这是我系统的问题,Windows 7中的相同代码不是问题,我只想找到一个更方便的解决方案,而不是将相同的代码添加到每个文件中

There's the code: 有代码:

#include <iostream>
#include <windows.h>
using namespace std;
int main() 
{
    SetConsoleOutputCP(65001);
    cout << "文本" ; //Output will be garbled code if there's no line above
    return 0; 
}

The console in most operating systems only expects ASCII character input. 大多数操作系统中的控制台仅要求输入ASCII字符。 In order to show some other char set you have to specify that in your code. 为了显示其他字符集,您必须在代码中指定它。 The SetConsoleOutputCP command sets the "code page" windows should read from. SetConsoleOutputCP命令设置窗口应从中读取的“代码页”。 By the way not all versions of windows have the same code for this command. 顺便说一下,并非所有版本的Windows都对此命令使用相同的代码。

Please refer to the documentation found here . 请参考此处的文档。

The documentation suggests using EnumSystemCodePages to make sure the code for that language exists on that system. 该文档建议使用EnumSystemCodePages确保该系统上存在该语言的代码。

PS Your English is very good :) PS您的英语非常好:)

EDIT 编辑

I tested your code on my computer with Visual Studio 2019 and got the following 我使用Visual Studio 2019在计算机上测试了您的代码,并获得了以下内容

Warning C4566 character represented by universal-character-name '\u6587' cannot be represented in the current code page (1255)   

even with the SetConsoleOutputCP command you added. 即使使用您添加的SetConsoleOutputCP命令。 I assume you need to have chines installed for this to work. 我认为您需要安装中文才能正常工作。 The problem is that I don't have the relevant code page for the windows console to look in for the char set. 问题是我没有用于Windows控制台的相关代码页来查找字符集。 see this answer and this answer . 看到这个答案这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM