在 Ubuntu(Linux)下 C++ 出现乱码,通常不是“编译器问题”,而是 字符编码不一致 导致的。下面按常见原因给你系统说明。
如果你在 Windows 写代码(GBK),传到 Ubuntu 编译,中文字符就会乱码。
✅ 解决:
file your_file.cpp
如果是:
ISO-8859 / GBK
转换为 UTF-8:
iconv -f GBK -t UTF-8 your_file.cpp -o new.cpp
或编辑器里另存为 UTF-8(无 BOM)
Ubuntu 终端默认是 UTF-8,但有时被改过。
检查:
locale
应该看到:
LANG=zh_CN.UTF-8
LC_ALL=zh_CN.UTF-8
如果不是:
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
cout << "中文" << endl;
这其实是 字节直接输出,是否乱码完全取决于:
✅ 推荐写法(C++11 起):
#include <iostream>
using namespace std;
int main() {
cout << u8"中文" << endl;
}
u8"..." 明确告诉编译器:这是 UTF-8 字符串。
g++ -finput-charset=UTF-8 -fexec-charset=UTF-8 main.cpp
含义:
-finput-charset:源码编码-fexec-charset:运行时常量字符串编码❌ 错误:
ifstream fin("中文.txt");
✅ 正确(C++17):
#include <filesystem>
using namespace std::filesystem;
ifstream fin(u8"中文.txt");
或使用 wstring + locale:
std::locale::global(std::locale("zh_CN.UTF-8"));
右下角确认是:
UTF-8
:set fileencoding=utf-8
| 检查项 | 正确值 |
|---|---|
| 源码编码 | UTF-8 |
| 终端编码 | UTF-8 |
| 编译器参数 | -fexec-charset=UTF-8 |
| 字符串 | u8"中文" |
| locale | zh_CN.UTF-8 |
#include <iostream>
using namespace std;
int main() {
setlocale(LC_ALL, "zh_CN.UTF-8");
cout << u8"你好,世界" << endl;
}
编译:
g++ -std=c++11 main.cpp
如果你愿意,可以把:
g++ 版本locale 输出贴出来,我可以直接帮你定位是哪一步出的问题。