情况:
- 当时vs中的c语言程序以utf-8的格式存储,而windows控制台的默认输出为GBK,两者不统一,这样就导致控制台的中文显示为乱码。
解决方法:
- 1.使用SetConsoleOutputCP(65001)函数,这样控制台的编码输出就为UTF-8了,编码相同之后,输出的内容就没有乱码了。
- 2.使用自定义的UTF-8转GBK的函数,保证字符串输出的时候是GBK的。别人写的转换函数
std::string GBKToUTF8(const std::string& strGBK)
{
std::string strOutUTF8 = "";
WCHAR* str1;
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
str1 = new WCHAR[n];
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
char* str2 = new char[n];
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
strOutUTF8 = str2;
delete[]str1;
str1 = NULL;
delete[]str2;
str2 = NULL;
return strOutUTF8;
}
std::string UTF8ToGBK(const std::string&strUTF8) {
std::string strOutGBK = "";
WCHAR* wstr;
int n = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
wstr = new WCHAR[n];
MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, wstr, n);
n = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[n];
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, n, NULL, NULL);
strOutGBK = str;
delete[] wstr;
wstr = NULL;
delete[] str;
str = NULL;
return strOutGBK;
}
|