How to write a std::string to a UTF-8 text file

前端 未结 9 1143
盖世英雄少女心
盖世英雄少女心 2020-12-01 01:04

I just want to write some few simple lines to a text file in C++, but I want them to be encoded in UTF-8. What is the easiest and simple way to do so?

9条回答
  •  抹茶落季
    2020-12-01 01:57

    My preference is to convert to and from a std::u32string and work with codepoints internally, then convert to utf8 when writing out to a file using these converting iterators I put on github.

    #include 
    
    int main()
    {
        using namespace utf;
    
        u32string u32_text = U"ɦΈ˪˪ʘ";
        // do stuff with string
        // convert to utf8 string
        utf32_to_utf8_iterator pos(u32_text.begin());
        utf32_to_utf8_iterator end(u32_text.end());
    
        u8string u8_text(pos, end);
    
        // write out utf8 to file.
        // ...
    }
    

提交回复
热议问题