Search code examples
c++unicodewchar-tostream

Writing Unicode Characters to an OStream


I'm working with unicode/wide characters and I'm trying to create a toString method (Java ::toString equiv). Will ostream handle wide characters, if so is there a way to warn the consumer of the stream that it is unicode coming out of it?


Solution

  • Neither ostream nor the rest of C++ know anything about Unicode. Usually you write a string conversion in C++ as follows:

    template<typename Char, typename Traits>
    std::basic_ostream<Char, Traits>&
    operator<<(std::basic_ostream<Char, Traits>& stream, const YourType& object) {
        return stream << object.a << object.b;  // or whatever
    }
    

    Whether you get something Unicode-like is up to the implementation. Streams in C++ are never text streams in the sense of Java, and C++'s strings are not strings in the sense of Java. If you want a real Unicode string, you might want to have a look at the ICU library.