About the problem of garbled characters in Chinese console output of Visual Studio 2019 and the solution
Environment: Windows11 Visual Studio 2019
There are garbled characters in Chinese output, which can be divided into two cases
1. Garbled characters appear in the output read from the .txt file
- The result is shown in the figure below:
- Analyze the cause of garbled characters
First of all, we have to know that Chinese under Windows is encoded in GBK, and VS2019 is also encoded in GBK, so it is best to use GBK to program Chinese in Windows.
The essence of Chinese garbled characters is the problem of encoding mismatch . It seems that if you use GBK to understand the utf-8 encoding, of course it cannot match.
- Solution
We know the reason and the solution is obvious: change the encoding of the .txt file utf-8 to the same GBK encoding as VS2019
first step:
Step two:
third step:
the fourth step:
re-run the code, test
output is correct
2. There are garbled characters in the output read from the Chinese string
Garbled characters appear when running the test.c file
char s[20] = "中文乱码问题";
printf("%s\n", s);
- Open the location of the test.c file
- Right click and select open as text file
- Same as the first operation above, change the encoding to GBK encoding , please refer to the above to modify the strikethrough format
3. When uploading git, garbled characters appear in gitee/github
To solve this problem, you only need to download a plug-in and exit VS2019 to restart.
Method: Open the management extension in the extension, search for: Force UTF-8 (NO BOM) and install it.
Summarize:
The solutions to the first two problems can effectively prevent garbled characters, but I think it is very troublesome to manually modify each time. I have not found a more effective way except for this method. Maybe I will try to use VScode to operate in the future.