这是我的 C++ 代码,我在其中尝试将接收到的文件路径编码为 utf-8。
#include <string>
#include <iostream>
using namespace std;
void latin1_to_utf8(unsigned char *in, unsigned char *out);
string encodeToUTF8(string _strToEncode);
int main(int argc,char* argv[])
{
// Code to receive fileName from Sockets
cout << "recvd ::: " << recvdFName << "\n";
string encStr = encodeToUTF8(recvdFName);
cout << "encoded :::" << encStr << "\n";
}
void latin1_to_utf8(unsigned char *in, unsigned char *out)
{
while (*in)
{
if (*in<128)
{
*out++=*in++;
}
else
{
*out++=0xc2+(*in>0xbf);
*out++=(*in++&0x3f)+0x80;
}
}
*out = '\0';
}
string encodeToUTF8(string _strToEncode)
{
int len= _strToEncode.length();
unsigned char* inpChar = new unsigned char[len+1];
unsigned char* outChar = new unsigned char[2*(len+1)];
memset(inpChar,'\0',len+1);
memset(outChar,'\0',2*(len+1));
memcpy(inpChar,_strToEncode.c_str(),len);
latin1_to_utf8(inpChar,outChar);
string _toRet = (const char*)(outChar);
delete[] inpChar;
delete[] outChar;
return _toRet;
}
输出是
recvd ::: /Users/zeus/ÄÈÊÑ.txt
encoded ::: /Users/zeus/AÌEÌEÌNÌ.txt
以上函数 latin1_to_utf8 作为解决方案提供 Convert ISO-8859-1 strings to UTF-8 in C/C++ ,看起来它有效。[答案被接受]。所以我想我一定是犯了一些错误,但我无法确定它是什么。请有人帮我解决这个问题。
我首先在 Codereview 中发布了这个问题,但我没有得到任何答案。很抱歉重复了。
最佳答案
您使用任何平台还是在 std 之上构建它?我相信很多人都使用这样的转换,因此有库。我强烈建议您使用 libraray,因为该库已经过测试并且通常使用最了解的方式。
我发现这样做的库是 boost locale
这是标准的。如果您使用 QT,我建议您为此使用 QT 转换库(它与平台无关)
如果你想自己做(你想看看它是如何工作的或出于任何其他原因) 1.确保分配内存! - 这在 C、C++ 中非常重要。由于您使用 iostream 使用 new 来分配内存并使用 delete 来释放它(这也很重要,C++ 无法确定何时释放它。这是开发人员的工作 - C++ 是硬核:D) 2. 检查您分配的内存大小是否正确。我希望 unicode 有更大的内存(它编码更多的符号,有时使用大数字)。 3. 如上所述,从某处(终端或文件)读取但在新文件中输出。之后,当您使用文本编辑器打开文件时,确保将编码设置为 utf-8(您的文本编辑器必须知道如何解释数据)
希望对您有所帮助。
关于C++ 字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14292207/