目录
[方法一: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为UTF-8](#方法一: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为UTF-8)
[方法二: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为GBK](#方法二: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为GBK)
1,问题
代码:
#include <iostream>
using namespace std;
int main() {
cout << "你好纯纯存储" << endl;
return 0;
}

报错原因:
源代码文件编码、编译器处理编码和终端输出编码这三者的统一
- 源码文件编码为UTF-8:
- 编译器默认用GBK解析源码,生成GBK编码的可执行文件
- Windows终端(PowerShell/CMD)默认使用GBK编码(codepage 936),无法正确解析UTF-8字节流

2,解决方案

方法一: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为UTF-8
1,源码main.cpp
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
SetConsoleOutputCP(65001); // 设置控制台输出为 UTF-8
cout << "你好纯纯存储" << endl;
return 0;
}
2,编译命令(可执行文件)
-finput-charset=UTF-8 指定源文件为UTF-8
-fexec-charset=UTF-8 指定可执行文件字符串为UTF-8
g++ -finput-charset=UTF-8 -fexec-charset=UTF-8 main.cpp -o main.exe
3,终端输出编码(运行可执行文件)

方法二: 设置 main.cpp 、 编译命令(可执行文件)、终端输出编码(运行可执行文件)均为GBK
1,源码main.cpp
#include <iostream>
using namespace std;
int main() {
cout << "你好" << endl;
return 0;
}
2,编译命令(可执行文件)
采用windows默认的GBK编译
g++ main.cpp -o main.exe
3,终端输出编码(运行可执行文件)
Windows默认GBK
.\main