我一直在嘗試了ISO-8859字符集轉換爲UTF-8從獲得的代碼: Convert ISO-8859-1 strings to UTF-8 in C/C++ 這裏是我的代碼:ISO-8859爲UTF-8轉換C++
#include <iostream>
#include <string>
using namespace std;
int main(int argc,char* argv[])
{
string fileName ="ħëlö";
int len= fileName.length();
char* in = new char[len+1];
char* out = new char[2*(len+1)];
memset(in,'\0',len+1);
memset(out,'\0',len+1);
memcpy(in,fileName.c_str(),2*(len+1));
while(*in)
{
cout << " ::: " << in ;
if(*in <128)
{
*out++ = *in++;
}
else
{
*out++ = 0xc2+(*in>0xbf);
*out++ = (*in++&0x3f)+0x80;
}
}
cout << "\n\n out ::: " << out << "\n";
*out = '\0';
}
但輸出是
::: ħëlö ::: ?ëlö ::: ëlö ::: ?lö ::: lö ::: ö ::: ?
out :::
輸出'out'應該是一個utf-8字符串,它不是。我得到這個在Mac OS X ..
我在這裏做錯了什麼..?
(1)缺少#include。 (2)你期望成爲什麼樣的產出?請澄清。 (3)它與osx(標籤)有什麼關係?順便說一句:證實了在Linux上與gcc的行爲4.7.2 –
steffen
我不知道std :: cout將與您的UTF-8編碼字符串很好的行爲。這可能是問題,而不是轉換代碼。 – Steve
在@ unwind的答案中修復指針問題後,請確保您的shell設置爲UTF-8:http://stackoverflow.com/questions/4606570/os-x-terminal-utf-8-issues – japreiss