首页 > 代码库 > CrossApp之VS2013不能输出中文,乱码,附加源码(一)

CrossApp之VS2013不能输出中文,乱码,附加源码(一)

VS2013可以使用iconv,也可以使用宽字节的方式来处理。

代码才是王道,直接贴了。。。

//
//  UTF8ToGBK.h
//  UTF8ToGBK
//
//  Created by kevin.
//
#pragma once

#include <iostream>
#include <stdio.h>
//string是c++ 的头文件,其内包含了一个string类,string s1就是建立一个string类的对象 
#include <string>
//cstring.h 是对应于旧C 头文件的std 版本
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
   #include <cstringt.h>
#else
   #include "cstring"
#endif

#include <locale>

#define LOG_NEW_LINE printf("\n")
using namespace std;

class UTF8ToGBK
{
public:
	UTF8ToGBK(void);
	~UTF8ToGBK(void);

	//将unicode编码的string转换成wstring
	static wstring stringToWstring(const string text);

	//将utf8格式编码转化成gbk,vs2010的默认的编码格式
	static string transferToGbk(const string text);
};


//
//  UTF8ToGBK.cpp
//  UTF8ToGBK
//
//  Created by kevin.
//
#include "UTF8ToGBK.h"


UTF8ToGBK::UTF8ToGBK(void)
{
}


UTF8ToGBK::~UTF8ToGBK(void)
{
}


//将string转换成wstring
wstring UTF8ToGBK::stringToWstring(const string str)
{
	setlocale(LC_ALL, "chs"); 
	const char* _Source = str.c_str();
	size_t _Dsize = str.size() + 1;
	wchar_t *_Dest = new wchar_t[_Dsize];
	wmemset(_Dest, 0, _Dsize);
	mbstowcs(_Dest,_Source,_Dsize);
	std::wstring result = _Dest;
	delete []_Dest;
	setlocale(LC_ALL, "C");
	return result;
}

//当在WIN32 平台下,将utf8格式编码转化成gbk,vs2010的默认的编码格式
string UTF8ToGBK::transferToGbk(const string text)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)

	wstring tes = stringToWstring(text);
	
	int asciSize = WideCharToMultiByte(CP_UTF8,0,tes.c_str(),tes.size(),NULL,0,NULL,NULL);
	if (asciSize == ERROR_NO_UNICODE_TRANSLATION || asciSize == 0)	
	{
		return string();
	}

	char *resultString = new char[asciSize];
	int conveResult = WideCharToMultiByte(CP_UTF8,0,tes.c_str(),tes.size(),resultString,asciSize,NULL,NULL);
	if (conveResult != asciSize)
	{
		return string();
	}
	string buffer = "";
	buffer.append(resultString,asciSize);

	delete[] resultString;
	return buffer;
#else
	return text;
#endif

	return text;
}



okk,测试代码如下,就拿一键创建的工程来做个示范。


void FirstViewController::viewDidLoad()
{
    // Do any additional setup after loading the view from it's nib.
	CCRect winRect = this->getView()->getBounds();
    CAImageView* imageView = CAImageView::createWithImage(CAImage::create("HelloWorld.png"));
    imageView->setFrame(winRect);
    this->getView()->addSubview(imageView);
    
    CALabel* label = CALabel::createWithCenter(CCRect(winRect.size.width*0.5, winRect.size.height*0.5-270, winRect.size.width, 200));
    label->setTextAlignment(CATextAlignmentCenter);
    label->setVerticalTextAlignmet(CAVerticalTextAlignmentCenter);
    label->setFontSize(72 * CROSSAPP_ADPTATION_RATIO);
	label->setText(UTF8ToGBK::transferToGbk("你好啊!").c_str());
    label->setColor(CAColor_white);
    this->getView()->insertSubview(label, 1);

	for (int i = 0; i < 100;i++	)
	{
		CCLog("%s : %d", UTF8ToGBK::transferToGbk("这是一个测试,童鞋!").c_str(),i);
	}
	
}