c++ - 如何将 std::string 转换为 wchar_t*
问题描述
std::regex regexpy("y:(.+?)\"");
std::smatch my;
regex_search(value.text, my, regexpy);
y = my[1];
std::wstring wide_string = std::wstring(y.begin(), y.end());
const wchar_t* p_my_string = wide_string.c_str();
wchar_t* my_string = const_cast<wchar_t*>(p_my_string);
URLDownloadToFile(my_string, aDest);
我正在使用Unicode
,源字符串的编码是ASCII
, UrlDownloadToFile
扩展为UrlDownloadToFileW (wchar_t*)
上面的代码在调试模式下编译,但有很多警告,如:
warning C4244: 'argument': conversion from 'wchar_t' to 'const _Elem', possible loss of data
所以我要问,我怎样才能将 a 转换std::string
为 a wchar_t
?
解决方案
首先,您不需要const_cast
, asURLDownloadToFileW()
将 aconst wchar_t*
作为输入,因此传递它将wide_string.c_str()
按原样工作:
URLDownloadToFile(..., wide_string.c_str(), ...);
话虽这么说,您正在用 astd::wstring
的各个char
值构建 a std::string
。这仅适用于 ASCII 字符 <= 127,而不会丢失数据,这些字符在 ASCII 和 Unicode 中具有相同的数值。对于非 ASCII 字符,您需要将数据实际转换为char
Unicode,例如 with MultiByteToWideChar()
(或等价),例如:
std::wstring to_wstring(const std::string &s)
{
std::wstring wide_string;
// NOTE: be sure to specify the correct codepage that the
// str::string data is actually encoded in...
int len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size(), NULL, 0);
if (len > 0) {
wide_string.resize(len);
MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size(), &wide_string[0], len);
}
return wide_string;
}
URLDownloadToFileW(..., to_wstring(y).c_str(), ...);
话虽如此,有一个更简单的解决方案。如果std::string
在用户的默认语言环境中编码,您可以简单地调用URLDownloadToFileA()
,将其按原样传递std::string
,并让操作系统为您处理转换,例如:
URLDownloadToFileA(..., y.c_str(), ...);
推荐阅读
- python - 实际数据未插入 MYSQL 数据库
- mysql - 无法登录 MySQL 服务器
- sql - SQL查询获取数据表列值中架构表行值的值
- google-bigquery - 使用实时管道时,无法从 gcs 向 bigquery 提供数据
- vue.js - Vue js - 如何在数组中迭代数组?
- android - 尽管使用了异步,为什么我仍然会收到 NetworkOnMainThreadException?
- ios - 如何删除突出显示的 pdf 注释?
- sql - 如何在两个表之间进行完全连接
- aws-glue - 使用 AWS Glue 在单独的元素中使用列名和值解析 xml
- java - 使用实现的类调用接口参数方法时出错