C++ TCHAR[] to string

hikizume picture hikizume · Oct 18, 2010 · Viewed 7.5k times · Source

I have this method which receives a path through a TCHAR szFileName[] variable, which contains something like C:\app\...\Failed\

I'd like to sort through it so I can verify if the name of the last folder on that path is in fact, "Failed"

I thought that using something like this would work:

std::wstring Path = szFileName;

string dirpath2;
dirpath2 = Path.substr(0,5); 

But I get the following error:

Error 6 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)

Needless to say, I'm very new to C++, and I've been looking for an answer for a while now, but I haven't had any luck, so any help would be appreciated :)

Answer

Konrad Rudolph picture Konrad Rudolph · Oct 18, 2010

Either you’re consistently using wstring (the wide character variant) or string (the “normal” variant).

Since you’re getting a TCHAR (which can be either wchar_t or char, depending on compiler flags), the appropriate type to use would be a tstring, but that doesn’t exist. However, you can define a typedef for it:

typedef std::basic_string<TCHAR> tstring;

Now you can consistently use the same string type, tstring, for all your operations.