17

How can I convert from CString to std::wstring?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
subbu
  • 3,229
  • 13
  • 49
  • 70
  • 2
    Please see this: http://stackoverflow.com/questions/258050/how-to-convert-cstring-and-stdstring-stdwstring-to-each-other – codaddict Jan 11 '10 at 10:48
  • 1
    and http://stackoverflow.com/questions/859304/convert-cstring-to-const-char – Idan K Jan 11 '10 at 10:52

4 Answers4

28

To convert CString to std::wstring:

CString hi("Hi");
std::wstring hi2(hi);

And to go the other way, use c_str():

std::wstring hi(L"Hi");
CString hi2(hi.c_str());
Andreas
  • 5,393
  • 9
  • 44
  • 53
DanDan
  • 10,462
  • 8
  • 53
  • 69
1

This should work as CString has operator LPCTSTR() defined:

CString s;
std::wstring s1 = s;
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Naveen
  • 74,600
  • 47
  • 176
  • 233
1

Try this:

std::wstring strString((LPCTSTR)strCString);
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ashish
  • 8,441
  • 12
  • 55
  • 92
  • 5
    Why use a C cast for that? A fellow-worker of mine once was in the position that he had to find explicit casts, as some of them didn't work on the platform he needed to port a 4MLoC project to. He praised everyone who used C++' explicit casts (you can grep for them) and fought hard to ban all C-style casts, since they were so hard to find. – sbi Jan 11 '10 at 11:10
0
CString s = _T("Привет");
USES_CONVERSION;
std::wstring ws(A2W((LPCTSTR)s));
Danil
  • 701
  • 8
  • 7