Конвертация между utf8 и cp1251 с сохранением результата
как сменить кодировку utf8 на cp1251 и обратно, чтобы буква 'ю' так и осталась буковой 'ю'? под буквой подразумевал любой символ русской раскладки
Ответы (1 шт):
Автор решения: anonymus
→ Ссылка
Пример использования стандартной библиотеки C++ для преобразования между UTF-8 и CP1251:
#include <iostream>
#include <Windows.h>
std::string ConvertCP1251ToUTF8(const std::string& str)
{
int len = MultiByteToWideChar(1251, 0, str.c_str(), -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
MultiByteToWideChar(1251, 0, str.c_str(), -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, 0, 0);
char* utf8 = new char[len];
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8, len, 0, 0);
std::string result(utf8);
delete[] wstr;
delete[] utf8;
return result;
}
std::string ConvertUTF8ToCP1251(const std::string& str)
{
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wstr, len);
len = WideCharToMultiByte(1251, 0, wstr, -1, NULL, 0, NULL, NULL);
char* cp1251 = new char[len];
WideCharToMultiByte(1251, 0, wstr, -1, cp1251, len, NULL, NULL);
std::string result(cp1251);
delete[] wstr;
delete[] cp1251;
return result;
}
int main()
{
SetConsoleOutputCP(CP_UTF8); // Установить кодировку консоли UTF-8
std::string original = "Hello, мир!";
std::string cp1251 = ConvertUTF8ToCP1251(original);
std::string utf8 = ConvertCP1251ToUTF8(cp1251);
std::cout << "Original in UTF-8: " << original << std::endl;
std::cout << "Converted to CP1251: " << cp1251 << std::endl;
std::cout << "Converted back to UTF-8: " << utf8 << std::endl;
return 0;
}
Обратите внимание, что этот код работает только на Windows, так как использует функции WinAPI для конвертации