[英]How to convert UTF8 char array to Windows 1252 char array
我是C ++的新手,所以我很抱歉提出愚蠢的問題。
我有一段文字:Павло
我在我正在處理的一段代碼中從控制台輸出中得到它。 我知道這是藏在后面的西里爾字母。 它的真正價值是“Петро”。
使用在線編碼檢測器,我發現要正確閱讀此文本,必須將其從UTF-8轉換為Windows 1252。
我該如何使用代碼?
我已經嘗試過了,它給出了一些結果,但是它輸出了5個問號(至少預期長度)
wchar_t *CodePageToUnicode(int codePage, const char *src)
{
if (!src) return 0;
int srcLen = strlen(src);
if (!srcLen)
{
wchar_t *w = new wchar_t[1];
w[0] = 0;
return w;
}
int requiredSize = MultiByteToWideChar(codePage,
0,
src, srcLen, 0, 0);
if (!requiredSize)
{
return 0;
}
wchar_t *w = new wchar_t[requiredSize + 1];
w[requiredSize] = 0;
int retval = MultiByteToWideChar(codePage,
0,
src, srcLen, w, requiredSize);
if (!retval)
{
delete[] w;
return 0;
}
return w;
}
char *UnicodeToCodePage(int codePage, const wchar_t *src)
{
if (!src) return 0;
int srcLen = wcslen(src);
if (!srcLen)
{
char *x = new char[1];
x[0] = '\0';
return x;
}
int requiredSize = WideCharToMultiByte(codePage,
0,
src, srcLen, 0, 0, 0, 0);
if (!requiredSize)
{
return 0;
}
char *x = new char[requiredSize + 1];
x[requiredSize] = 0;
int retval = WideCharToMultiByte(codePage,
0,
src, srcLen, x, requiredSize, 0, 0);
if (!retval)
{
delete[] x;
return 0;
}
return x;
}
int main()
{
const char *text = "Павло";
// Now convert utf-8 back to ANSI:
wchar_t *wText2 = CodePageToUnicode(65001, text);
char *ansiText = UnicodeToCodePage(1252, wText2);
cout << ansiText;
_getch();
}
也嘗試過這個,但是不能正常工作
int main()
{
const char *orig = "Павло";
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
std::wstring strUTF(wcstring);
const wchar_t* szWCHAR = strUTF.c_str();
cout << szWCHAR << '\n';
char *buffer = new char[origsize / 2 + 1];
WideCharToMultiByte(CP_ACP, 0, szWCHAR, -1, buffer, 256, NULL, NULL);
cout << buffer;
_getch();
}
這是打印問題。 您的第一個函數是正確的,可以對其進行測試MessageBoxW
:
wchar_t *wbuf = CodePageToUnicode(CP_UTF8, "Павло");
if(wbuf)
{
MessageBoxW(0, wbuf, 0, 0);
delete[]buf;
}
輸出量
"Павло"
(與您所說的不一樣!)
您可以使用std::wcout
打印寬字符,或簡化使用1251代碼頁進行打印的功能,如下所示:
#include <iostream>
#include <string>
#include <Windows.h>
int main()
{
char *buf = "Павло";
int size;
size = MultiByteToWideChar(CP_UTF8, 0, buf, -1, 0, 0);
std::wstring wstr(size, 0);
MultiByteToWideChar(CP_UTF8, 0, buf, -1, &wstr[0], size);
int codepage = 1251;
size = WideCharToMultiByte(codepage, 0, &wstr[0], -1, 0, 0, 0, 0);
std::string str(size, 0);
WideCharToMultiByte(codepage, 0, &wstr[0], -1, &str[0], size, 0, 0);
SetConsoleOutputCP(codepage);
std::cout << str << "\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.