C++中文转Unicode,并以string类型输出

#include "pch.h"
#include <iostream>
#include<string>
#include <windows.h>
#include <comdef.h> 
using namespace std;

string ch_to_unicode(char *chn);

void main()
{
	char chn[] = "豫";
	string unicode= ch_to_unicode(chn);
	cout << "unicode=" << unicode << endl;
}

string ch_to_unicode(char *chn)
{
	int sum = 0;
	int chnSize = strlen(chn);
	DWORD wcharSize = MultiByteToWideChar(CP_ACP, 0, chn, chnSize, NULL, 0);
	wchar_t * wcharunicode = new wchar_t[wcharSize];
	wmemset(wcharunicode, 0, wcharSize);
	//转unicode
	MultiByteToWideChar(CP_ACP, 0, chn, chnSize, wcharunicode, wcharSize);
	//wchar_t转char*
	_bstr_t tochar(*wcharunicode);
	char* charunicode = tochar;
	//10转16
	for (int i = 0; charunicode[i] != '\0'; i++)
	{
		sum = sum * 10 + charunicode[i] - '0';
	}
	char *hexunicode = new char[10];
	sprintf(hexunicode, "%x", sum);
	//char*转string
	string unicode = hexunicode;
	unicode = "\\u" + unicode;
	return unicode;
}

猜你喜欢

转载自blog.csdn.net/maitianpt/article/details/83478026
今日推荐