0
TCHAR buf[MAX_PATH];
int aFolder = CSIDL_APPDATA;
if (SHGetFolderPath(NULL, aFolder, NULL, SHGFP_TYPE_CURRENT, buf) != S_OK)
    *buf = '\0';

// buf     wchar_t
std::wstring str(&buf[0]); //convert to wstring
std::string str2(str.begin(), str.end()); //and convert to string.

std::string str3 = "\\settings.ini";
auto dir = str2 + str3;

warning:

conversion from 'wchar_t' to 'const _Elem', possible loss of data
1>          with
1>          [
1>              _Elem=char
1>          ]

What other way can I do this conversion without "possible loss of data"? I have also tried to use SHGetFolderPathW() but it returns the same warning.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    That's not how any of this works, you would just get a "string" that barely makes sense. Use `SHGetFolderPathA` instead to pull the ANSI version right away. – IWonderWhatThisAPIDoes Feb 15 '21 at 15:02
  • 1
    [WideCharToMultibyte](https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte) – 273K Feb 15 '21 at 15:04
  • 1
    You should also note that `ShGetFolderPath` is deprecated and its use is discouraged. Use [`SHGetKnownFolderPath`](https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath) instead. – spectras Feb 15 '21 at 15:05

1 Answers1

0

std::wstring is usually either UTF-16 or UTF-32. std::string is usually UTF-8. What you are doing is not a proper way of converting between those encodings. See UTF8 to/from wide char conversion in STL

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93