繁体   English   中英

c + +使用iconv从UTF-8转换为wstring

[英]c++ convert from UTF-8 to wstring using iconv

我有一个运行以下程序的C ++ Linux应用程序:

int main()
{
  using namespace std;
  char str[] = "¡Hola!";

  wchar_t wstr[50];

  size_t rc;

  memset(wstr, 0, sizeof(wstr));

  rc = mbstowcs(wstr, str, 50);

  cout << "mbstowcs results: ";
  cout << "rc = " << rc << endl;
  cout << "str:" << str  << endl;
  wcout << L"wstr:" << wstr  << endl;
  setlocale(LC_CTYPE,"");
  iconv_t cd = iconv_open("WCHAR_T", "UTF-8");
  cout << "iconv_open errno = "<< errno << endl;

  char *s = str;
  char *t = (char *)wstr;
  size_t s1 = strlen(str);
  size_t s2 = 50;

  rc = iconv(cd, &s, &s1, &t, &s2);

  cout << "iconv results: ";
  cout << "rc = " << rc << endl;
  cout << "str:" << str  << endl;
  wcout << L"wstr:" << wstr  << endl;

}

我想将UTF-8字符向量转换为wstring,但是上面的代码返回此结果:

 mbstowcs results: rc = 18446744073709551615
    str:¡Hola!
    wstr:
    iconv_open errno = 2
    iconv results: rc = 0
    str:¡Hola!
    wstr:�Hola!

iconv结果将第一个字符转换为另一个字符。

注意:如果我在UCS-4 -INTERNAL中替换WCHAR_T,则wstr不包含任何内容。

有什么帮助吗?

谢谢!

不用看iconv文档(到目前为止,无需使用它),我希望您的输入( char str[] = "¡Hola!"; )不会被编码为多字节字符串-更有可能是一个简单的ANSI字符串,使用您的本地/当前代码页代表'¡' 换句话说:在您现有的字符串中(使用const char[] ), '¡'存储在单个字节中,其值大于127。但是mbstowcs()可能希望它使用2个字节来表示适当的'¡' (暂时不检查),并且您的'¡'使用的值甚至可能不是您期望的/不允许的值。

我希望错误会在那里发生,因为mbcstowcs()应该返回转换后的字符串中的字符数-但是“ 18446744073709551615”太长了。 如果是这样,则在使用适当的文本定义自己的宽字符串并使用该文本时,也应该能够正确使用iconv( wchar_t wstr[] = L"¡Hola!"; )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM