[英]How to convert UnicodeString to windows-1251 using ICU library in c++ Linux?
[英]Library ICU on Ubuntu doesn't want to convert from Unicode to windows-1251
我正在使用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對象的過程中,總是出現以下錯誤:“無法獲取字符集.....”。
如何解決此錯誤? 我在Google中搜索,但未找到任何內容。
我使用以下代碼來獲取別名文件中包含的所有可用轉換器的列表:
for(int i = 0; i < ucnv_countAvailable(); ++i)
{
printf(" %s \n", ucnv_getAvailableName(i));
}
我在此列表中未找到“ windows-1251”。 如何添加此編碼?
您需要使用宏U_SUCCESS
而不是僅測試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-1998
和ibm-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
調用以查看所有名稱/別名的很長的列表)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.