How to convert unicode code points to utf-8 in c++?

前端 未结 6 476
暖寄归人
暖寄归人 2020-12-18 05:08

I have an array consisting of unicode code points

unsigned short array[3]={0x20ac,0x20ab,0x20ac};

I just want this to be converted as utf-8

6条回答
  •  难免孤独
    2020-12-18 05:33

    With std c++

    #include 
    #include 
    #include 
    
    int main()
    {
        typedef std::codecvt Convert;
        std::wstring w = L"\u20ac\u20ab\u20ac";
        std::locale locale("en_GB.utf8");
        const Convert& convert = std::use_facet(locale);
    
        std::mbstate_t state;
        const wchar_t* from_ptr;
        char* to_ptr;
        std::vector result(3 * w.size() + 1, 0);
        Convert::result convert_result = convert.out(state,
              w.c_str(), w.c_str() + w.size(), from_ptr,
              result.data(), result.data() + result.size(), to_ptr);
    
        if (convert_result == Convert::ok)
            std::cout << result.data() << std::endl;
        else std::cout << "Failure: " << convert_result << std::endl;
    }
    

提交回复
热议问题