中文乱码的问题

关于cocos2d-x中文乱码的问题

cocos2d-x中文显示乱码的问题大家都遇到过,网上的方法有很多,这里给大家整理两种简单实用的方法。
常用的解决方法多半是将编码格式改为UTF-8,但是在我的几次试验中出现了有的时候可以,有的时候不行的情况,具体原因上不是很清楚,但是从网上大家反映的情况来看这种方法的确是不可靠的。
现在给大家整理两种经过验证之后有效的方法:
1、键值对的方法
2、格式转换的方法
键值对的方法
这个是比较标准和通用的方法,就是由键值找中文。
方法是在Resources目录下新建一个string.xml文件,格式可以仿照Android中的strings.xml写,如下。(注意格式保存为UTF-8)
          <dict>
                <key>Hello</key>
                <string>你好!</string>
          </dict>  
再在工程中使用的地方用键值对获取中文字符即可:
CCDictionary *strings = CCDictionary::createWithContentsOfFile("strings.xml");  
//读取Hello键中的值     objectForKey根据key,获取对应的string  
const char *hello = ((CCString*)strings->objectForKey("Hello"))->_string.c_str();  


CCLabelTTF  *labelHello = CCLabelTTF::create(hello, "Arial", 24);  
labelHello->setPosition( ccp(size.width / 2, size.height /2) );  
this->addChild(labelHello, 1); 
格式转换
即添加函数将中文字符转换成UTF-8格式,代码如下。
void WStrToUTF8(std::string& dest, const std::wstring& src){  
    dest.clear();  
   
    for (size_t i = 0; i < src.size(); i++){  
        wchar_t w = src[i];  
        if (w <= 0x7f)  
            dest.push_back((char)w);  
        else if (w <= 0x7ff)  
        {  
            dest.push_back(0xc0 | ((w >> 6)& 0x1f));  
            dest.push_back(0x80| (w & 0x3f));  
        }  
        else if (w <= 0xffff)  
        {  
            dest.push_back(0xe0 | ((w >> 12)& 0x0f));  
            dest.push_back(0x80| ((w >> 6) & 0x3f));  
            dest.push_back(0x80| (w & 0x3f));  
        }  
        else if (sizeof(wchar_t) > 2 && w <= 0x10ffff)  
        {  
            dest.push_back(0xf0 | ((w >> 18)& 0x07)); // wchar_t 4-bytes situation  
            dest.push_back(0x80| ((w >> 12) & 0x3f));  
            dest.push_back(0x80| ((w >> 6) & 0x3f));  
            dest.push_back(0x80| (w & 0x3f));  
        }  
        else 
            dest.push_back('?');  
    }  
}  
std::string WStrToUTF8(const std::wstring& str)  
{  
    std::string result;  
    WStrToUTF8(result, str);  
    return result;
 
}
使用范例 :
 std::string timeStr1 = WStrToUTF8(L"你好!"); 
timeStr1 即为我们所要的以UTF-8格式编码的结果。(注意:字符串前要加L,L表示宽字节,表示后面的每个字符占用两个字节,正好满足汉字输出要求)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值