首页 > 解决方案 > 如何将 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,源字符串的编码是ASCIIUrlDownloadToFile扩展为UrlDownloadToFileW (wchar_t*)上面的代码在调试模式下编译,但有很多警告,如:

warning C4244: 'argument': conversion from 'wchar_t' to 'const _Elem', possible loss of data

所以我要问,我怎样才能将 a 转换std::string为 a wchar_t

标签: c++

解决方案


首先,您不需要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 字符,您需要将数据实际转换charUnicode,例如 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(), ...);

推荐阅读