0

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

2 Answers2

1

You have to use iterator to make copy. This is how you can do it.

char* pathAppData = nullptr;
size_t sz = 0;
_dupenv_s(&pathAppData, &sz, "APPDATA");
std::string sPathAppData(pathAppData);
sPathAppData.append("\\MyApplication");

std::wstring wPathAppData(begin(sPathAppData), end(sPathAppData));
wcout << wPathAppData << endl;
  • `std::wstring wPathAppData(pathAppData, pathAppData + strlen(pathAppData));` would also work, and avoids creating a temporary `std::string`. It works because pointers are iterators too. – john Apr 16 '20 at 07:54
  • Thank you for your answer, it works but I validate the @Robertas answer because it more direct. –  Apr 16 '20 at 08:04
1

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

Robertas
  • 1,164
  • 3
  • 11
  • 26