-1

I'm doing on a win32 application, and has a edit control that accepts unicode text input. I use the following code to get the text to a std::string:

WCHAR out[50] = {};
GetDlgItemTextW(hwnd, ID_Edit, out, 50);
wstring myWString(out);
string myString(ws.begin(), ws.end());

In the dubugger, I can see that myWString is fine when input is unicode text, but myString is currupted.

How can I convert it correctly?

EDIT:

OK, rather then fooling with string, I use wstring instead. But another problem arise:

I have another code that was using string, cout and cin to get user input in consle, now wstring, wcin and wcout breaks the non-ASCII text input and out put part...

For my code it was:

string myString;
//...
cin >> myString;
//...
cout << myString;

Changing to:

wstring myString;
//...
wcin >> myString;
//...
wcout << myString;

The input and output text are corrupted if the user use non-ASCII characters.

Dia
  • 851
  • 1
  • 15
  • 35
  • Why do you want to convert in the first place? If you need to work with internationalized, non-ASCII text, use `wstring` for it. – Igor Tandetnik Nov 24 '16 at 04:28
  • 3
    You can use WideCharToMultiByte API – Asesh Nov 24 '16 at 04:33
  • This question is too broad without knowing the source and destination encoding. – MrEricSir Nov 24 '16 at 04:33
  • @MrEricSir: Since it's coming from GetDlgItemTextW, the source encoding is UTF16. But the destination encoding is important. – Mooing Duck Nov 24 '16 at 04:34
  • If using Visual Studio, you need [_setmode](http://stackoverflow.com/a/9051543/4603670). Or see this [answer](http://stackoverflow.com/a/40626557/4603670) for other compilers. Or just use `MessageBoxW` for Windows programming. You may want to define `UNICODE` in your project so that Windows API functions will default to `UNICODE` (`W` version) – Barmak Shemirani Nov 24 '16 at 09:50

1 Answers1

0

OK, after google around, I can finally using cin and wstring together without unicode problem. I add the lines:

setlocale(LC_ALL, "");
ios_base::sync_with_stdio(false);
wcin.imbue(locale(""));
wcout.imbue(locale(""));

and the wcin is good now:

wstring myString;
getline(wcin, myString);
//...
wcin >> myString;
//...
wcout << myString;
Dia
  • 851
  • 1
  • 15
  • 35