简体   繁体   English

将 Unicode 字符写入 OStream

[英]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 ).我正在使用 unicode/wide 字符,并且正在尝试创建一个 toString 方法( 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? ostream 是否会处理宽字符,如果是这样,有没有办法警告流的使用者它是从它出来的 unicode?

Neither ostream nor the rest of C++ know anything about Unicode. ostream和 C++ 的其余部分都对 Unicode 一无所知。 Usually you write a string conversion in C++ as follows:通常你用 C++ 写一个字符串转换如下:

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.你是否得到类似 Unicode 的东西取决于实现。 Streams in C++ are never text streams in the sense of Java, and C++'s strings are not strings in the sense of Java. C++中的流绝不是Java意义上的文本流,C++的字符串也不是Java意义上的字符串。 If you want a real Unicode string, you might want to have a look at the ICU library .如果您想要一个真正的 Unicode 字符串,您可能需要查看ICU 库

Wide strings are non-portable and better be avoided in C++.宽字符串是不可移植的,最好在 C++ 中避免使用。 They can be UTF-16, UTF-32 or even non-Unicode depending on platform.它们可以是 UTF-16、UTF-32 甚至非 Unicode,具体取决于平台。

The common approach in C++ is to use UTF-8 encoded multibyte char strings internally and, if necessary, do transcoding at system boundaries. C++ 中的常见方法是在内部使用 UTF-8 编码的多字节char字符串,如有必要,在系统边界进行转码。 Most modern systems such as Linux and macOS work well with UTF-8 so passing them to an output stream works.大多数现代系统(例如 Linux 和 macOS)与 UTF-8 配合良好,因此将它们传递给输出流是可行的。 Windows is the most problematic because of legacy code pages.由于遗留代码页,Windows 是最有问题的。 You can use Boost Nowide or the {fmt} library for portable UTF-8 output.您可以将Boost Nowide{fmt} 库用于可移植的 UTF-8 输出。

Disclaimer : I'm the author of {fmt}.免责声明:我是 {fmt} 的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM