Search code examples
c++stringvisual-c++type-conversionwstring

Why I can't construct a wstring from char*


According I build fill a char* from this code :

char* pathAppData = nullptr;
size_t sz = 0;
_dupenv_s(&pathAppData, &sz, "APPDATA");

I can easily construct a string with this code and append this string in the future :

std::string sPathAppData(pathAppData);
sPathAppData.append("\\MyApplication");

But I can't create a wstring from this code. Why is so complicated to work with wstring ? I am going crazy with all theses types.

std::wstring wPathAppData(pathAppData); // Impossible

Solution

  • You could use wchar_t directly and use corresponding wchar_t supported API to retrieve data directly to wchar_t and then construct wstring. _dupenv_s function has a wide counterpart - _wdupenv_s.

    Your code then would look like this:

    wchar_t* pathAppData = nullptr;
    size_t sz = 0;
    _wdupenv_s(&pathAppData, &sz, L"APPDATA");
    std::wstring wPathAppData(pathAppData);
    wPathAppData.append(L"\\MyApplication")
    

    Also this could be an interesting read: std::wstring VS std::string