【发布时间】:2016-08-26 09:11:31
【问题描述】:
我正在尝试将字符串“aÜ”从 UTF-8 转换为 CP1251 通过C++ 库iconv.h 使用 TRANSLIT,结果我得到字符串“a?”,当期待“aU”时。
当我在这台计算机上使用 php 脚本 <?php echo iconv("UTF-8", "Windows-1251//TRANSLIT", "Ü");> 时,我得到“aU”字符串作为结果。
代码如下:
#include <cstdlib>
#include <iconv.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
using namespace std;
int IConvert(char *buf,char *outbuf, size_t len, const char *from, const char *to)
{
iconv_t iconv_cd;
if ((iconv_cd = iconv_open(to, from)) == (iconv_t) -1) {
printf("Cannot open iconv from %s to %s\n", from, to);
return 0;
}
char *inbuf = buf;
size_t inlen = len;
size_t outlen = len;
size_t res = 0;
while (inlen > 0 && outlen > 0) {
res = iconv(iconv_cd, &inbuf, &inlen, &outbuf, &outlen);
if (res == 0)
break;
if (res == (size_t) (-1)) {
if (errno != EILSEQ && errno != EINVAL) {
iconv_close(iconv_cd);
*outbuf = '\0';
printf("Erorr %s (%s)\n", strerror(errno), from);
return 0;
} else if (inbuf < outbuf) {
iconv_close(iconv_cd);
*outbuf = '\0';
printf("Erorr %s (inbuf < outbuf)\n", strerror(errno));
return 0;
}
}
if (inlen > 0 && outlen > 0) {
*outbuf++ = *inbuf++;
inlen--;
outlen--;
}
}
iconv_close(iconv_cd);
*outbuf = '\0';
return 1;
}
int main(int argc, char** argv) {
char* line = "\u00C0a\u00DC";
char* from = (char*) malloc(strlen(from)+1);
char* to = (char*) malloc(strlen(from)+1);
strcpy(from, line);
printf("%s\n", from);
IConvert(from, to, strlen(from)+1, "UTF-8", "CP1251//TRANSLIT");
printf("%s\n", to);
return 0;
}
知道可能是什么问题吗?
【问题讨论】:
-
我会尝试用其文字 UTF-8 编码替换
Ü。 -
它没有帮助,我从 = "\u00C0aÜ"; 重写了行 char*;输入行是 ÀaÜ,输出是 ?a?
-
您将输入缓冲区用作输出缓冲区,因此在转换源字符串时会踩到它。
-
我重写了,没有帮助。更新了第一篇文章。
-
char* from = (char*) malloc(strlen(from)+1);?真的吗?
标签: c++ linux character-encoding iconv