VS Code:4个中文乱码问题及解决方法-转载
https://www.jianshu.com/p/6a2c21cc07bb
1. 背景
凡是编程软件,特别是国外的软件,都有或多或少的中文乱码问题(毕竟程序都是用英文写的)。现提出VS Code编程过程中遇到的4个中文乱码问题以及解决方法。
2. 问题
2.1 打开文件后,中文显示乱码
#include <iostream>
using namespace std;
int main()
{
int sum = 0, value = 0;
//ֻ�������ļ�������EOF���������������ʱ�������Ƴ�ѭ����������
//���������ֺ�ctrl+z�Ƴ�ѭ��
while (cin >> value) {
sum += value;
}
cout << "Sum is: " << sum << endl;
return 0;
}
注意:当打开文件,其内容中文乱码时,不要Ctrl+S保存文件。因为那样会保存乱码,使其无法恢复中文。
解决方法1:点击右下角中的“UTF-8”,选择“通过编码重新打开”,输入“GB 2312”,选择“Simplified Chinese(GB 2312)”即可。


解决方法2:打开“查看”>“命令面板”,输入“setting”, 选择“首选项:打开设置(json)”,输入如下语句并保存即可。
"files.autoGuessEncoding": true


提示:设置完成后,若文件还是中文乱码,关闭文件重新打开即可。
2.2 终端命令行运行时出现中文乱码
g++ 1.cpp -o 1.exe; ./1.exe
原因:在终端使用命令行运行程序时,文件为UTF-8编码,而非GB2312编码。
解决方法1:点击右下角的"UTF-8",选择”通过编码保存“,输入”GB 2312“,选择“Simplified Chinese(GB 2312)”,将UTF-8转换成GB 2312。


解决方法2:在命令行前面添加chcp 65001用于换码。
chcp 65001; g++ 1.cpp -o 1.exe; ./1.exe
2.3 点击运行键运行程序出现中文乱码
原因:从终端可发现,点击运行键运行程序与直接用命令行运行程序相类似,其中文乱码也是因为使用UTF-8编码。
解决方法1:点击右下角的"UTF-8",选择”通过编码保存“,输入”GB 2312“,选择“Simplified Chinese(GB 2312)”,将UTF-8转换成GB 2312。

解决方法2:打开“查看”>“命令面板”,输入“setting”, 选择“首选项:打开设置(json)”,在"code-runner.executorMap"中的“cpp”添加“chcp 65001”。

修改前:
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
修改后:
"cpp": "cd $dir && chcp 65001 && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
2.4 调试时,终端出现中文乱码或无法输出中文
原因:文件使用GB2312编码,而非UTF-8编码。
解决方法:点击右下角的"GB2312",选择”通过编码保存“,输入”utf-8“,选择”UTF-8 utf8“即可。


3. 总结
- 打开文件时,设置"files.autoGuessEncoding": true令VS Code自动选择合适编码方式。
- 通过命令行或运行键运行程序时,若是UTF-8编码会造成中文乱码,需要在运行命令中添加“chcp 65001”,或者将UTF-8编码转换成GB2312编码。
- VS Code默认编码是UTF-8,调试时也是使用UTF-8,可以输出中文。