Search code examples
c++unicodeutf-16stdstring

How to output/Input multibyte symbols?


After a lot of searching I start using that weird code:

ofstream myfile;
    string chars =  "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
    myfile.open ("alphabet.txt");
    for (int i = 0; i < 66; i+=2) {
        myfile << chars[i] <<chars[i+1] << "\n";
    }
    myfile.close();

But is there really no way to get a wide character out of std::string?


Solution

  • This worked on my machine. My source code file is in UTF-8. The string is in UTF-16. The output is in UTF-16LE.

    C++ has gotten a little better over time handling Unicode strings, but still has a lot of room for improvement.

    #include <fstream>
    #include <string>
    
    using std::ofstream;
    using std::string;
    
    int main() {
        auto chars = u"абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
        auto myfile = ofstream("alphabet.txt");
        for (char16_t const* p = chars; *p; ++p) {
            auto c = *p;
            auto cc = reinterpret_cast<char const*>(&c);
            myfile.write(cc, sizeof c);
        }
        myfile.close();
    }