how to make the windows console works with utf-8 encoded project

the console of the windows os is not working in the utf-8 encoding, by default. When you force your code be encoded with utf-8, the console will not print what you want.
Here is how to configure your project encoding with utf-8, and work as it is in windows.

configure visual sutdio to encoding with utf-8

add a .editorconfig file to you project. visual studio will use the encoding as the configuration file asked.

put the code in the .editorconfig

# Rules in this file were initially inferred by Visual Studio IntelliCode from the D:\data\playGround\playGround_y9kp\playGround_y9kp\ codebase based on best match to current usage at 2022/8/27
# You can modify the rules from these initially generated values to suit your own policies
# You can learn more about editorconfig here: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference
# [*.cs]

[*.{js,py,cpp, hpp, c, h}]
charset = utf-8

set your project build and execute in utf-8

this will be configured in the project property page.

tell the working encoding at the very beginning of you code

method 0

int main(int argc, char** argv)
{
    system("chcp 65001"); // set the console work with utf-8 encoding.
    cout << "aaaaaaaaaa" << endl;
    cout << "噫吁戏危乎高哉" << endl;
    cout << "aaaaaaaaaa" << endl;
    return 0;
}

method 1

use the gragma

#pragma execution_character_set("utf-8")
int main(int argc, char** argv)
{
    cout << "aaaaaaaaaa" << endl;
    cout << "噫吁戏危乎高哉" << endl;
    cout << "aaaaaaaaaa" << endl;
    return 0;
}

start to run you code and check the result

reference

c++ - Is there an easy way to write UTF-8 octets in Visual Studio? - Stack Overflow
https://stackoverflow.com/questions/19987448/is-there-an-easy-way-to-write-utf-8-octets-in-visual-studio

(118条消息) #pragma execution_character_set解决中文乱码_lyingcloud的博客-CSDN博客_execution_character_set
https://blog.csdn.net/chenhongwei610/article/details/101512960

execution_character_set pragma | Microsoft Docs
https://docs.microsoft.com/en-us/cpp/preprocessor/execution-character-set?view=msvc-170

/utf-8 (Set source and execution character sets to UTF-8) | Microsoft Docs
https://docs.microsoft.com/en-us/cpp/build/reference/utf-8-set-source-and-executable-character-sets-to-utf-8?view=msvc-170

posted on 2022-08-27 21:11  yusisc  阅读(37)  评论(0编辑  收藏  举报

导航