-2

I want to convert CString to WCHAR* or std::string to WCHAR* in Visual Studio C++ MFC Application. I found in stackoverflow that it only has the solution for convert to wchar_t*.

Please help me. Thank you!

Noob
  • 23
  • 3
  • 5
    `WCHAR` is used in Windows as an alias for `wchar_t`. You might be interested in studying [this common types for Windows](https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types) reference. – Some programmer dude Jan 19 '22 at 04:33
  • If you are asking how to convert from 8bit strings to 16bit strings then you can use CA2WEX from ATL : https://learn.microsoft.com/en-us/cpp/atl/reference/ca2wex-class?view=msvc-170 – Pepijn Kramer Jan 19 '22 at 04:38
  • 3
    `CString` is a typedef that either aliases `CStringA` or `CStringW`. An answer to this question would be different for either case. – IInspectable Jan 19 '22 at 06:59

2 Answers2

0

When you use CString, you could access the CW2A ATL macro,which converts CString to string.

CString theCStr;
std::string STDStr( CW2A( theCStr.GetString(), CP_UTF8 ) );

Or refer to this document.

Yujian Yao - MSFT
  • 945
  • 1
  • 3
  • 9
  • The question is asking how to convert to `WCHAR*`. `CW2A` will not do that. And it's the wrong macro, too. If you're using a `CString` (as opposed to a `CStringW`), the compatible conversion macro is called `CT2A`. – IInspectable Jan 19 '22 at 10:20
  • This [issue](https://social.msdn.microsoft.com/Forums/en-US/46ef3191-aff1-4532-9953-42ddc313e09d/convert-a-cstring-to-wchar?forum=vssmartdevicesnative) explains how to convert cstring to wchar*. – Yujian Yao - MSFT Jan 20 '22 at 05:26
  • That entry suffers from the exact same inconsistency as this proposed answer. If you're using the ambient character set, you have to use it **consistently**. [This Q&A](https://stackoverflow.com/q/258050/1889329) is far more useful. And it's on-site, too. – IInspectable Jan 20 '22 at 08:42
0

I believe CString class can do such conversion:

CStringA a = "ANSI";
CStringW w(a);
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
  • I believe this doesn't address the question. As I read it, the OP needs to convert a `CString` to a `WCHAR*`, but only found solutions that would convert to `wchar_t*`. Apparently, they aren't realizing that `WCHAR*` and `wchar_t*` are the same thing on Windows. – IInspectable Jan 20 '22 at 08:44
  • @IInspectable possibly; I was just trying to show a way without using error-prone macros. – Vlad Feinstein Jan 20 '22 at 17:34
  • 1
    Sure, except, this has pitfalls just as well. "ANSI" is only half of a character encoding. The other half is missing (and implied, and possibly wrong). – IInspectable Jan 20 '22 at 18:04