Ubuntu上的库ICU不希望从Unicode转换为windows-1251

问题描述 投票:0回答:1

我正在使用ICU库,我需要从Unicode转换为windows-1251,我写了这个简单的代码:

#include <unicode/unistr.h>
#include <unicode/ucnv.h>

int main(int argc, char** argv)
{
    UErrorCode status = U_ZERO_ERROR;
    UConverter *pConvert = ucnv_open("windows-1251", &status);
    if (status)
    {
        printf("Failed to obtain char set converter: %d\r\n", status);
        return false;
    }
}

我总是在创建UConverter对象时遇到此错误:“无法获取char set .....”。

如何解决这个错误?我在谷歌搜索但没有找到任何东西。

我使用此代码获取别名文件中包含的所有可用转换器的列表:

for(int i = 0; i < ucnv_countAvailable(); ++i)
    {
        printf("   %s  \n", ucnv_getAvailableName(i));
    }

我没有在这个列表中找到“windows-1251”。如何添加此编码?

c++ unicode icu
1个回答
0
投票

你需要use the macro U_SUCCESS instead of just testing status。 ICU中的负错误代码是警告:

typedef enum UErrorCode {
  // ...
  U_AMBIGUOUS_ALIAS_WARNING = -122

这很好用:

auto converter = ucnv_open("windows-1251", &error);
if (U_SUCCESS(error))
{
  printf("Success! %s\n", ucnv_getName(converter, &error));
} 

打印出来:

Success! ibm-5347_P100-1998

你得到“模糊”警告的原因是因为“windows-1251”是多个规范名称(ibm-5347_P100-1998ibm-1251_P100-1995)的别名。您可以通过使用“别名”功能更新样本来查看此内容:

int main()
{
  UErrorCode error{ U_ZERO_ERROR };
  const auto n = ucnv_countAvailable();
  for (int i = 0; i < n; ++i)
  {
    auto s = ucnv_getAvailableName(i);
    const auto m = ucnv_countAliases(s, &error);
    if (U_SUCCESS(error))
    {
      for (int j = 0; j < m; ++j)
      {
        auto a = ucnv_getAlias(s, j, &error);
        if (U_SUCCESS(error) && strstr(a, "windows-1251"))
          printf("%s --> %s\n", s, a);
      }
    }
  }
}

(删除strstr调用以查看所有名称/别名的很长列表)。

© www.soinside.com 2019 - 2024. All rights reserved.