How to convert from UTF-8 to ANSI using standard c++

后端 未结 4 831
孤街浪徒
孤街浪徒 2020-12-15 13:46

I have some strings read from the database, stored in a char* and in UTF-8 format (you know, \"á\" is encoded as 0xC3 0xA1). But, in order to write them to a file, I first n

4条回答
  •  没有蜡笔的小新
    2020-12-15 14:13

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    std::string utf8_to_string(const char *utf8str, const locale& loc){
        // UTF-8 to wstring
        wstring_convert> wconv;
        wstring wstr = wconv.from_bytes(utf8str);
        // wstring to string
        vector buf(wstr.size());
        use_facet>(loc).narrow(wstr.data(), wstr.data() + wstr.size(), '?', buf.data());
        return string(buf.data(), buf.size());
    }
    
    int main(int argc, char* argv[]){
        std::string ansi;
        char utf8txt[] = {0xc3, 0xa1, 0};
    
        // I guess you want to use Windows-1252 encoding...
        ansi = utf8_to_string(utf8txt, locale(".1252"));
        // Now do something with the string
        return 0;
    }
    

提交回复
热议问题