String 2 LPCWSTR ?!

09/08/2016 12:29 juliansen#1
Hello guys im searching for method to convert a std::string 2 a lpcwstr
google just refers me in a circle hope someone of you can give a correct clear anwser :) Error say : no suitable constructor exists to convert from "const char*" to std::basic_string....

ty very mutch for trying to help out people :handsdown:
09/08/2016 12:43 Jeoni#2
Just convert your std::string to an std::wstring and provide the method you're about to call with .c_str(). However, that error is a bit odd for what you're trying, so if you got problems you'd best include the code causing them.
Code:
#include <string>
...
std::string x("This is my string.");
std::wstring y;
for (char c : x) y.push_back(c);
ImportantMethodTakingLPCWSTR(y.c_str());
...
There are other ways, but this is pretty straightforward I suppose. You could also manage the memory of the LPCWSTR yourself instead of letting this do std::wstring. As you're a beginner as it seems I wouldn't recommend it though.
With best regards
Jeoni
09/11/2016 01:25 Terreox#3
You can just use [Only registered and activated users can see links. Click Here To Register...] to convert between std::string and std::wstring using your encoding of choice.

Little sample using UTF-8:

Code:
#include <codecvt>
#include <locale>

int main()
{
    std::string stringToConvert = "Hello World";

    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> utf8_conv;

    std::wstring converted = utf8_conv.from_bytes(stringToConvert);
}
As LPWCSTR is just a const wchar_t* you can then use converted.c_str() to get your LPWCSTR value out of converted.

Hope this suits your needs! :)
09/17/2016 18:06 vaynz#4
Hey. First of all std::string is a class which is meant for easier handling of a string.
This means there is no conversion to a built-in type.

The cleanest method is described above by Terreox. It's always a good practice too use the STL.
A more low-level attempt would be to use MultiByteToWideChar or a function implemented in CRT, mbstowcs to convert a given character-sequence from utf8 to utf16 (unicode) and then construct a string object.