有点前景:我的任务需要将UTF-8 XML文件转换为UTF-16 (当然有适当的标题)。因此,我搜索了将UTF-8转换为UTF-16的常用方法,并发现应该使用<codecvt>中的模板。
但是现在,当它是已弃用时,我想知道执行相同任务的新的共同方式是什么?
(根本不介意使用Boost,但除此之外,我更愿意尽可能靠近标准库。)
发布于 2017-03-22 08:44:35
不推荐使用来自std::codecvt本身的<locale>模板。对于UTF-8到UTF-16,仍然存在std::codecvt<char16_t, char, std::mbstate_t>的专门化.
但是,由于std::wstring_convert和std::wbuffer_convert与标准的转换面一起被废弃,所以没有任何简单的方法可以使用方面来转换字符串。
因此,正如Bolas已经回答的:自己实现它(或者您可以像往常一样使用第三方库)或者继续使用不推荐的API。
发布于 2017-04-01 05:07:55
,别担心,
根据同一信息源
此库组件应保留到附件D,旁边是,直到适当的替换被标准化的为止。
所以,你仍然可以使用它,直到一个新的标准化,更安全的版本完成。
发布于 2021-10-01 18:07:14
由于没有人真正回答这个问题并提供可用的替换代码,这里有一个,但它只适用于Windows:
#include <string>
#include <stdexcept>
#include <Windows.h>
std::wstring string_to_wide_string(const std::string& string)
{
if (string.empty())
{
return L"";
}
const auto size_needed = MultiByteToWideChar(CP_UTF8, 0, &string.at(0), (int)string.size(), nullptr, 0);
if (size_needed <= 0)
{
throw std::runtime_error("MultiByteToWideChar() failed: " + std::to_string(size_needed));
}
std::wstring result(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &string.at(0), (int)string.size(), &result.at(0), size_needed);
return result;
}
std::string wide_string_to_string(const std::wstring& wide_string)
{
if (wide_string.empty())
{
return "";
}
const auto size_needed = WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0), (int)wide_string.size(), nullptr, 0, nullptr, nullptr);
if (size_needed <= 0)
{
throw std::runtime_error("WideCharToMultiByte() failed: " + std::to_string(size_needed));
}
std::string result(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0), (int)wide_string.size(), &result.at(0), size_needed, nullptr, nullptr);
return result;
}https://stackoverflow.com/questions/42946335
复制相似问题