What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?

爱⌒轻易说出口 提交于 2019-12-17 12:48:44

问题


This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar.


回答1:


MultiByteToWideChar but also see "A few of the gotchas of MultiByteToWideChar".




回答2:


The simplest way is to use the conversion macros:

  • CW2A
  • CA2W
  • etc...

MSDN




回答3:


TCHAR is a Microsoft-specific typedef for either char or wchar_t (a wide character).

Conversion to char depends on which of these it actually is. If TCHAR is actually a char, then you can do a simple cast, but if it is truly a wchar_t, you'll need a routine to convert between character sets. See the function MultiByteToWideChar()




回答4:


There are a few answers in this post as well, especially if you're looking for a cross-platform solution:

UTF8 to/from wide char conversion in STL




回答5:


Although in this particular situation I think the TChar is a wide character I'll only need to do the conversion if it isn't. which I gotta check somehow.

if (sizeof(TCHAR) != sizeof(wchar_t))
{  .... }

The cool thing about that is both sizes of the equals are constants, which means that the compiler will handle (and remove) the if(), and if they are equal, remove everything inside the braces




回答6:


Here is the CPP code that duplicates _TCHAR * argv[] to char * argn[].

http://www.wincli.com/?p=72

If you adopting old code to Windows, simple use define mentioned in the code as optional.




回答7:


You can put condition in your code

ifdef _UNICODE

{ //DO LIKE TCHAR IS WIDE CHAR } ELSE { //DO LIKE TCHAR IS CHAR }




回答8:


I realize this is an old thread, but it didn't get me the "right" answer, so am adding it now.

The way this appears to be done now is to use the TEXT macro. The example for FindFirstFile at msdn points this out. http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx



来源:https://stackoverflow.com/questions/159442/what-is-the-simplest-way-to-convert-char-to-from-tchar-in-c-cms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!