在 Linux 下用 C++ 处理编码格式,通常涉及 源文件编码、终端编码、字符串编码、文件读写编码 四个方面。下面按常见场景给你一个实用配置指南。
使用编辑器保存为 UTF-8(无 BOM):
UTF-8:set fileencoding=utf-8
:set nobomb
g++ -finput-charset=UTF-8 -fexec-charset=UTF-8 main.cpp
⚠ 默认 Linux 就是 UTF-8,一般不用特别设置
locale
正常应看到:
LANG=en_US.UTF-8
LC_ALL=zh_CN.UTF-8
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
std::string(UTF-8 字节流)std::string s = "中文"; // UTF-8
✅ Linux 下 std::string 默认就是 UTF-8 字节
std::wstring#include <locale>
std::locale::global(std::locale(""));
std::wstring ws = L"中文";
⚠ 不推荐在 Linux 大量用 wstring,UTF-8 + string 更简单
std::ifstream fin("test.txt");
fin.imbue(std::locale("")); // 使用系统 locale
std::ofstream fout("out.txt");
fout.imbue(std::locale(""));
fout << "中文";
| 原因 | 解决 |
|---|---|
| 源文件不是 UTF-8 | 转成 UTF-8 |
| 终端不是 UTF-8 | export LANG=...UTF-8 |
| Windows 文件到 Linux | 去 BOM |
| 混用 GBK / UTF-8 | 统一 UTF-8 |
#include <iconv.h>
boost::localestd::codecvt(C++17 已弃用)✅ 全栈 UTF-8
std::string 存 UTF-8✅ 避免:
wchar_t 滥用如果你有 具体场景(如:中文乱码 / 文件读写 / socket / Qt / 日志系统),我可以给你 针对性代码。