C++控制台输出中文时乱码的解决方案
起因
使用cmd程序进行编码和C++程序编码(源文件编码)不同。cmd程序默认的编码格式是gbk,而C++程序编码格式是utf-8。
解决方案
1、C++源代码里更改cmd编码
源码实例:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
system("chcp 65001");
cout << "测试" << endl;
return 0;
}
同时打开项目,点击【属性】
附加选项中添加:/utf-8。
效果:
TIPS:会显示chcp命令的返回文本,效果不佳。
2、使用window库中带有的SetConsoleOutputCP(推荐)
源码实例:
#include <iostream>
#include <windows.h>//SetConsoleOutputCP函数所在库函数,让cmd程序的编码更为utf-8
using std::cout;
using std::endl;
using std::cin;
int main()
{
SetConsoleOutputCP(65001);
cout << "测试" << endl;
return 0;
}
效果: