簡體   English   中英

如何將 std::string 轉換為 wchar_t*

[英]How to convert std::string to 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

那么我想問一下,如何將std::string轉換為wchar_t

首先,你不需要const_cast ,因為URLDownloadToFileW()需要一個const wchar_t*作為輸入,所以傳遞它wide_string.c_str()將按wide_string.c_str()工作:

URLDownloadToFile(..., wide_string.c_str(), ...);

話雖如此,您正在使用std::string的各個char值按原樣構造一個std::wstring 這僅適用於 ASCII 字符 <= 127 且不會丟失數據,這些字符在 ASCII 和 Unicode 中具有相同的數值。 對於非 ASCII 字符,您需要char數據實際轉換為 Unicode,例如使用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(), ...);

有一個跨平台的解決方案。 您可以使用std::mbtowc

std::wstring convert_mb_to_wc(std::string s) {
    std::wstring out;
    std::mbtowc(nullptr, 0, 0);
    int offset;
    size_t index = 0;
    for (wchar_t wc;
           (offset = std::mbtowc(&wc, &s[index], s.size() - index)) > 0;
           index += offset) {
        out.push_back(wc);
    }
    return out;
}

改編自 cppreference.com 上的示例,網址https://en.cppreference.com/w/cpp/string/multibyte/mbtowc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM