如何在C ++中将UTF-16中的字符串转换为UTF-8 [英] How do I convert a string in UTF-16 to UTF-8 in C++
本文介绍了如何在C ++中将UTF-16中的字符串转换为UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
STDMETHODIMP CFileSystemAPI::setRRConfig( BSTR config_str, VARIANT* ret )
{
mReportReaderFactory.reset( new sbis::report_reader::ReportReaderFactory() );
USES_CONVERSION;
std::string configuration_str = W2A( config_str );
但是在config_str中,我在UTF-16中得到了一个字符串.如何在这段代码中将其转换为UTF-8?
But in config_str I get a string in UTF-16. How can I convert it to UTF-8 in this piece of code?
推荐答案
您可以执行以下操作
std::string WstrToUtf8Str(const std::wstring& wstr)
{
std::string retStr;
if (!wstr.empty())
{
int sizeRequired = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (sizeRequired > 0)
{
std::vector<char> utf8String(sizeRequired);
int bytesConverted = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),
-1, &utf8String[0], utf8String.size(), NULL,
NULL);
if (bytesConverted != 0)
{
retStr = &utf8String[0];
}
else
{
std::stringstream err;
err << __FUNCTION__
<< " std::string WstrToUtf8Str failed to convert wstring '"
<< wstr.c_str() << L"'";
throw std::runtime_error( err.str() );
}
}
}
return retStr;
}
您可以将BSTR用作std :: wstring
You can give your BSTR to the function as a std::wstring
这篇关于如何在C ++中将UTF-16中的字符串转换为UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文