tgbot-cpp icon indicating copy to clipboard operation
tgbot-cpp copied to clipboard

StringTools: add functions to convert utf-8 to cp1251 on Windows

Open reo7sp opened this issue 7 years ago • 1 comments

  • [ ] utf-8 -> cp1251
  • [ ] utf-8 <- cp1251

reo7sp avatar May 11 '17 08:05 reo7sp

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>

std::string Utf8_to_cp1251(std::string input)
{
    const char *str = input.c_str();
    std::string res;
    int result_u, result_c;

    result_u = MultiByteToWideChar(CP_UTF8, 0, str, -1, 0, 0);
    if (!result_u)
        return 0;

    wchar_t *ures = new wchar_t[result_u];

    if (!MultiByteToWideChar(CP_UTF8, 0, str, -1, ures, result_u))
    {
        delete[] ures;
        return 0;
    }

    result_c = WideCharToMultiByte(1251, 0, ures, -1, 0, 0, 0, 0);
    if (!result_c)
    {
        delete[] ures;
        return 0;
    }

    char *cres = new char[result_c];

    if (!WideCharToMultiByte(1251, 0, ures, -1, cres, result_c, 0, 0))
    {
        delete[] cres;
        return 0;
    }
    delete[] ures;
    res.append(cres);
    delete[] cres;
    return res;
}

reo7sp avatar May 13 '17 22:05 reo7sp