在 Strings(通常指 C/C++ 里的 std::string / C 字符串)输出乱码,常见原因和解决办法如下,你可以对照排查。
现象:中文、日文等字符变成问号 ? 或乱码。
原因:
✅ 解决办法
#include <windows.h>
int main() {
SetConsoleOutputCP(65001); // UTF-8
}
现象:输出一堆乱码或程序崩溃
char s[] = {'a', 'b', 'c'};
printf("%s\n", s); // ❌ 没有 '\0'
✅ 正确写法
char s[] = {'a', 'b', 'c', '\0'};
或
char s[] = "abc";
现象:std::string 显示乱码
std::string s = u8"中文";
std::cout << s << std::endl; // 可能乱码
✅ 推荐写法
#include <iostream>
#include <string>
int main() {
SetConsoleOutputCP(65001);
std::string s = u8"中文";
std::cout << s << std::endl;
}
现象:wstring 输出乱码
std::wstring s = L"中文";
std::cout << s; // ❌
✅ 正确方式
#include <iostream>
#include <io.h>
#include <fcntl.h>
int main() {
_setmode(_fileno(stdout), _O_U16TEXT);
std::wstring s = L"中文";
std::wcout << s << std::endl;
}
现象:字符串常量本身就是乱码
✅ 检查
char* p = nullptr;
printf("%s", p); // ❌
✅ 确保字符串内存有效
\0 结尾string / wstring你可以直接贴:
1️⃣ 使用的语言(C / C++ / Java / Python)
2️⃣ 输出代码
3️⃣ 乱码截图或示例
我可以 直接帮你改到能跑 ✅