gpt4 book ai didi

c++ - 被 Unicode、Boost、C++、codecvts 难倒

转载 作者:IT老高 更新时间:2023-10-28 23:15:50 27 4
gpt4 key购买 nike

在 C++ 中,我想使用 Unicode 来做事。因此,在掉进 Unicode 的兔子洞之后,我最终陷入了困惑、头痛和语言环境的火车残骸中。

但在 Boost 中,我遇到了一个不幸的问题,即尝试使用 Unicode 文件路径并尝试将 Boost 程序选项库与 Unicode 输入一起使用。我已经阅读了有关语言环境、codecvts、Unicode 编码和 Boost 主题的所有内容。

我目前的尝试是使用一个 codecvt,它接受一个 UTF-8 字符串并将其转换为平台的编码(POSIX 上的 UTF-8,Windows 上的 UTF-16),我一直在尝试避免 wchar_t.

我实际上得到的最接近的是尝试使用 Boost.Locale 执行此操作,以便在输出时从 UTF-8 字符串转换为 UTF-32 字符串。

#include <string>
#include <boost/locale.hpp>
#include <locale>

int main(void)
{
std::string data("Testing, 㤹");

std::locale fromLoc = boost::locale::generator().generate("en_US.UTF-8");
std::locale toLoc = boost::locale::generator().generate("en_US.UTF-32");

typedef std::codecvt<wchar_t, char, mbstate_t> cvtType;
cvtType const* toCvt = &std::use_facet<cvtType>(toLoc);

std::locale convLoc = std::locale(fromLoc, toCvt);

std::cout.imbue(convLoc);
std::cout << data << std::endl;

// Output is unconverted -- what?

return 0;
}

我认为我使用宽字符进行了其他类型的转换,但我真的不知道我在做什么。我现在不知道什么是适合这项工作的工具。帮忙?

最佳答案

好的,经过漫长的几个月后,我想通了,我想在未来帮助人们。

首先,codecvt 的做法是错误的。 Boost.Locale 在其 boost::locale::conv 命名空间中提供了一种在字符集之间进行转换的简单方法。这是一个示例(还有其他不基于语言环境的示例)。

#include <boost/locale.hpp>
namespace loc = boost::locale;

int main(void)
{
loc::generator gen;
std::locale blah = gen.generate("en_US.utf-32");

std::string UTF8String = "Tésting!";
// from_utf will also work with wide strings as it uses the character size
// to detect the encoding.
std::string converted = loc::conv::from_utf(UTF8String, blah);

// Outputs a UTF-32 string.
std::cout << converted << std::endl;

return 0;
}

如您所见,如果将“en_US.utf-32”替换为“”,它将在用户的语言环境中输出。

我仍然不知道如何让 std::cout 一直这样做,但是 Boost.Locale 的 translate() 函数在用户的语言环境中输出。

至于使用UTF-8字符串跨平台的文件系统,看来是可以的,here's a link to how to do it .

关于c++ - 被 Unicode、Boost、C++、codecvts 难倒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7859638/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com