我们来让openframeworks自带的ofxml也支持中文解析

前几天接到的小任务,让OF自带的ofXml解析器也支持中文。

问题:在解析xml文件的中文时,即使文件时utf-8格式的也会乱码显示。并且如果储存的数据是路径,并不能正确的找到。

问题解决:用一个函数将解析器解析到的字符串转换成普通的string格式即可。函数如下:

string ofApp::UTF8_To_string(const std::string & str)
{
	int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);

	wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
	memset(pwBuf, 0, nwLen * 2 + 2);

	MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);

	int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

	char * pBuf = new char[nLen + 1];
	memset(pBuf, 0, nLen + 1);

	WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

	std::string retStr = pBuf;

	delete[]pBuf;
	delete[]pwBuf;

	pBuf = NULL;
	pwBuf = NULL;

	return retStr;
}
这样对获得的字符串都用这个函数处理一下,就可以获得正确的结果了。

猜你喜欢

转载自blog.csdn.net/cupidyzw97/article/details/53244793
今日推荐