0

I'm writing a MFC project by Visual Studio 2015, character set config to "Use Unicode Character set"

I need to convert from std::string to LPWSTR to use with some MFC object properties like LVITEM::pszText in CListCtrl, AfxMessageBox, ... So I use this snipset from internet:

String str = "Hello world!";
std::wstring wname(str.begin(), str.end());
LPWSTR lStr = const_cast<wchar_t*>(wname.c_str());
MessageBox(lStr);

This approach work fine. But the problem is that every time I need to convert I must rewrite these statement, and I put this snipset into a function:

LPWSTR convertLPWSTR(std::string &str) {
    std::wstring wname(str.begin(), str.end());
    return const_cast<wchar_t*>(wname.c_str());
}
/...
String str = "Hello world!";
LPWSTR lStr = convertLPWSTR(str);
MessageBox(lStr);

But the message box output an error string (like error font)
:

Any one know how to fix this? Thanks!

phibao37
  • 2,230
  • 4
  • 26
  • 35
  • I would recommend using [link](http://stackoverflow.com/a/27296/6460438 ) – Greg Jun 30 '16 at 09:19
  • 3
    A few notes on your implementation: `1` It seems that the habit to construct a wide character string from a narrow character string by simply widening the data type (completely ignoring the character **encoding**) is hard to kill. Stop doing it. It does not work as you expect. `2` Your `convertLPWSTR` implementation returns a pointer to a local object. That's undefined behavior. `3` The solution is trivially easy: `MessageBox(CString(str.c_str()));` – IInspectable Jun 30 '16 at 09:22
  • 3
    Do you know what `wstring`, `LPWSTR`, `c_str` do or are you programming by trial and error? – user253751 Jun 30 '16 at 09:27
  • 2
    @Greg: That answer is needlessly complex. In MFC there is the [CStringT](https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx) class template, that provides all the conversion c'tors you would ever need. And since you can pass a `CString` anywhere a C-style string is expected (including variable argument lists), it is really all you need. – IInspectable Jun 30 '16 at 09:31

1 Answers1

-4

Why don't you use

CString str = _T("Hello world!") ;
Irminsul
  • 171
  • 9
  • This does not convert from `std::string` (in case you wonder about the downvote). – IInspectable Jun 30 '16 at 14:01
  • The question isn't *"Should I be using `std::string`?"*. The question is *"I have a `std::string` and need to convert to a wide character string. How do I do that?"* Any way, I should really stop leaving comments, explaining why I downvoted an answer. It always leads to explaining it twice. – IInspectable Jun 30 '16 at 14:32