将 Unicode 字符写入 OStream

发布于 2024-09-10 04:28:54 字数 209 浏览 5 评论 0原文

我正在使用 unicode/wide 字符,并尝试创建一个 toString 方法(Java : :toString 等效)。 ostream 会处理宽字符吗?如果是的话,有没有办法警告流的使用者它是来自其中的 unicode?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪异←思 2024-09-17 04:28:54

ostream 和 C++ 的其余部分都不了解 Unicode。通常,您用 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
}

是否获得类似 Unicode 的内容取决于实现。 C++中的流从来都不是Java意义上的文本流,C++中的字符串也不是Java意义上的字符串。如果您想要真正的 Unicode 字符串,您可能需要查看 ICU 库

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.

为你拒绝所有暧昧 2024-09-17 04:28:54

宽字符串是不可移植的,在 C++ 中最好避免使用。它们可以是 UTF-16、UTF-32 甚至非 Unicode,具体取决于平台。

C++ 中的常见方法是在内部使用 UTF-8 编码的多字节 char 字符串,并在必要时在系统边界进行转码。大多数现代系统(例如 Linux 和 macOS)都可以很好地使用 UTF-8,因此将它们传递到输出流是可行的。由于遗留代码页,Windows 是最有问题的。您可以使用 Boost Nowide用于可移植 UTF-8 输出的 {fmt} 库

免责声明:我是{fmt}的作者。

Wide strings are non-portable and better be avoided in C++. They can be UTF-16, UTF-32 or even non-Unicode depending on platform.

The common approach in C++ is to use UTF-8 encoded multibyte char strings internally and, if necessary, do transcoding at system boundaries. Most modern systems such as Linux and macOS work well with UTF-8 so passing them to an output stream works. Windows is the most problematic because of legacy code pages. You can use Boost Nowide or the {fmt} library for portable UTF-8 output.

Disclaimer: I'm the author of {fmt}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文