# Win32 String Types

This topic is 3444 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I wrote this simple static class to abstract the code to display an Open File Dialog box, but I was just wondering if anyone who is a little more familiar with win32 string types could look at this and see if there is anything here that I'm doing wrong. The code works compiles, runs, and functions correctly, but strings in general tend to confuse me so I just wanted to know if I went about this the right way. #include <windows.h> #include <string> #include <atlstr.h> class OpenFile { public: static bool FileDialog(LPCWSTR Filter, std::string& Filename) { OPENFILENAME ofn; ZeroMemory(&ofn,sizeof(ofn)); char szFileName[MAX_PATH]=""; ofn.lStructSize = sizeof(ofn); ofn.lpstrFilter = Filter; ofn.lpstrFile = (LPWSTR)szFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST; ofn.lpstrDefExt = L"pgm"; if(GetOpenFileName(&ofn)) { Filename = CW2A(ofn.lpstrFile); //Convert the LPWSTR to a std::string return true; //File was selected. } return false; //File was not selected. } };

##### Share on other sites
You declare szFileName as char, then you force-cast it to WCHAR*. That doesn't look fine.

Either you use unicode, or you use ASCII, or you use TCHAR which changes depending on which you use. If you want to use unicode strings everywhere, you should use std::wstring instead of std::string. Or if you want to use ascii strings, use LPCSTR for all params along with std::string. Or if you want to switch between the two depending on whether _UNICODE is defined, use TCHAR, LPCTSTR, LPTSTR and #define tstring conditionally to be either string or wstring.

What I usually do is something like this:

char szPath[MAX_PATH] = {0};OPENFILENAME ofn = {0};ofn.lpstrFile = szPath;ofn.nMaxFile = MAX_PATH - 1;

##### Share on other sites
Thanks for the reply and the link. CW2A() is macro defined in "atlstr.h" and is used to convert a LPWSTR to a std::string. I think it involves converting multi byte characters to w_char, but I'm not really sure.