0

I have to convert a TCHAR variable (which is a path retrieved with OpenBrowseDir) into a std::string. I'm currently having this code which works. I'm using WideCharToMultiByte.

TCHAR path[MAX_PATH];
OpenBrowseDir(path);
/*conversion from TCHAR to std::string*/
char ch[MAX_PATH];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP, 0, path, -1, ch, MAX_PATH, &DefChar, NULL);
string spath(ch);

On my project TCHAR is wchar_t.

In OpenBrowseDir I'm opening a browse dialog so the user can select a directory. I'm using a variable BROWSEINFO bi, and bi.pszDisplayName is of type TCHAR.

Are there other better solutions?

Laura Maftei
  • 1,863
  • 1
  • 15
  • 25
  • 1
    What's wrong with this approach? Of course, we don't know what `OpenBrowseDir` is. I also wonder why you are using `TCHAR` and then calling `WideCharToMultiByte`. If you always compile for UNICODE, why use `TCHAR`? And if you always compile for UNICODE, why use `std::string`. This seems very confused. – David Heffernan Oct 07 '14 at 08:16
  • Thanks, i edited the question and added more details about OpenBrowseDir. I'm using std::string further in my code with c_str(), that's why i need it. – Laura Maftei Oct 07 '14 at 09:55
  • Don't you care about international text? Surely you should be using `std::wstring`. I cannot understand why you want to use ANSI. That makes no sense to me at all. And surely you are using `SHBrowseForFolder` if you have `BROWSEINFO`. – David Heffernan Oct 07 '14 at 09:57
  • Yes, I'm using SHBrowseForFolder, that's why i need TCHAR. – Laura Maftei Oct 07 '14 at 10:46
  • You don't need to use `TCHAR` to call `SHBrowseForFolder`. I think you need to step back and learn more about encodings and character sets. I don't think you understand the issues well enough to make good decisions. – David Heffernan Oct 07 '14 at 10:48
  • Why not using TCHAR with BROWSEINFO? Its member pszDisplayName is LPTSTR. – Laura Maftei Oct 07 '14 at 16:27
  • Use TCHAR if you need to support Windows 98. Otherwise use the native Unicode API. With the W suffixed functions and types and wchar_t. – David Heffernan Oct 07 '14 at 17:13
  • Consider using UTF-8 everywhere. http://utf8everywhere.org/#how – T Percival Oct 07 '14 at 20:10

0 Answers0