Skipher Skipher - 1 year ago 175
C++ Question

Converting std::string to a typedef of wchar_t*

I am reading in a file directory from the user through the console, and I must store the value in a

pxcCHAR*
variable, which is the SDK's
typedef
for
wchar_t*
.

I found that I can do the conversion from
std::string
to
std::wstring
by doing the following.

#include <iostream>

int main(){
std::string stringPath;
std::getline(std::cin, stringPath);
std::wstring wstrPath = std::wstring(stringPath.begin(), stringPath.end());
const wchar_t* wcharPath = wstrPath.c_str();
return 0;
}


When I run this code, I see these values through debugging.

stringPath= "C:/Users/"
wstrPath= L"C:/Users/"
wcharPath= 0x00b20038 L"C:/Users/"


Where is the value concatenated to the front of
wcharPath
coming from?

Furthermore,

Because
pxcCHAR*
is a
typedef
for
wchar_t*
, I thought it would be okay to simply do this:

pxcCHAR* mFilePath = wcharPath;


However, I get a message saying that "const wchar_t*" cannot be used to initialize an entity of type "pxcCHAR*".

I expected implicit conversion to work, but it doesn't. How can I overcome this error?

Answer Source

Using std::wstring(stringPath.begin(), stringPath.end()) is the wrong way to deal with string conversions, unless you can guarantee that you are only dealing with 7bit ASCII data (which is not the case with the filesystem). This type of conversion doesn't account for character encodings at all. The correct way to convert a std::string to std::wstring is to use std::wstring_convert, MultiByteToWideChar(), or other equivalent. There are plenty of examples of this if you look around.

Better would be to just use std::wstring to begin with instead of std::string, eg:

#include <iostream>
#include <string>

int main(){
    std::wstring stringPath;
    std::getline(std::wcin, stringPath);
    const wchar_t* wcharPath = stringPath.c_str();
    return 0;
}

Where is the value concatenated to the front of wcharPath coming from?

The debugger. It is simply showing you the memory address that the pointer is pointing at, followed by the actual character data at that address.

I get a message saying that "const wchar_t*" cannot be used to initialize an entity of type "pxcCHAR*".

That means pxcCHAR is not a typedef of const wchar_t, but is more likely a typedef of just wchar_t by itself. You cannot assign a const pointer to a non-const pointer, regardless of the type used. If you need to make this kind of assignment, you have to type-cast the const away, such as with const_cast:

pxcCHAR* mFilePath = const_cast<wchar_t*>(wcharPath);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download